function addJavascript(jsname,pos)
{
	var th = document.getElementsByTagName(pos)[0];
	var s = document.createElement('script');
	s.setAttribute('type','text/javascript');
	s.setAttribute('src',jsname);
	th.appendChild(s);
}

function selectAll(theField)
{
	var tempval=eval("document."+theField)
	tempval.focus()
	tempval.select()
	therange=tempval.createTextRange()
	therange.execCommand("Copy")
}

function showhide(id) {
  if (document.getElementById) {
    obj = document.getElementById(id);
    if (obj.style.display == "") {
      obj.style.display = "none";
    } else {
      obj.style.display = "";
    }
  }
}

function m_menu_s_s()
{
	document.cookie = 'm_menu_s=1';
}
function m_menu_s_h()
{
	document.cookie = 'm_menu_s=0';
}
function m_menu_f()
{
	var m_menu_s = getCookie('m_menu_s');
	if(m_menu_s == '1')
	{
		$('#c_user_menu_b').toggle();
		$('#c_user_menu_a').toggle();
	}
}

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

function showLoading()
{
	document.getElementById("loading").style.display='none';
}
function showLoader()
{
	document.getElementById("loading").style.display='block';
}

function onClicked() 
{
      var links = document.body.getElementsByTagName("A");
      for (var i=0; i<links.length; i++) 
	  {
            links[i].onmousedown=function() 
			{
				document.getElementById("loading").style.display='block';
            }
      }
	  var links = document.body.getElementsByTagName("li");
      for (var i=0; i<links.length; i++) 
	  {
            links[i].onmousedown=function() 
			{
				document.getElementById("loading").style.display='none';
            }
      }
}

function menuChange(id1, id2) {
  var status1 = document.getElementById(id1).style.display; 
  var status2 = document.getElementById(id2).style.display;
  if (id1 == "menu1") {
	  if ((status1 == 'none') && (status2 == 'none')) {
		showhide(id1); return;
	  }
	  if ((status1 != 'none') && (status2 != 'none')) {
		showhide(id2); return;
	  }
	   if ((status1 == 'none') && (status2 != 'none')) {
		showhide(id1);  showhide(id2); return;
	  }
  }
  else if (id1 == "menu2") {
	  if ((status1 == 'none') && (status2 == 'none')) {
		showhide(id1); return;
	  }
	  if ((status1 != 'none') && (status2 != 'none')) {
		showhide(id2); return;
	  }
	   if ((status1 == 'none') && (status2 != 'none')) {
		showhide(id1);  showhide(id2); return;
	  }
  }
}
function videoChange(id1, id2, id3, id4) {
  var status1 = document.getElementById(id1).style.display; 
  var status2 = document.getElementById(id2).style.display;
  var status3 = document.getElementById(id3).style.display; 
  var status4 = document.getElementById(id4).style.display;
  if (id1 == "vmenu1") {
	  if ((status1 == 'none')) {
		  showhide(id1);
	  }
	  if ((status2 != 'none')) {
		  showhide(id2);
	  }
	  if ((status3 != 'none')) {
		  showhide(id3);
	  }
	  if ((status4 != 'none')) {
		  showhide(id4);
	  }
  }
  else if (id1 == "vmenu2") {
	  if ((status1 == 'none')) {
		  showhide(id1);
	  }
	  if ((status2 != 'none')) {
		  showhide(id2);
	  }
	  if ((status3 != 'none')) {
		  showhide(id3);
	  }
	  if ((status4 != 'none')) {
		  showhide(id4);
	  }
  }
  else if (id1 == "vmenu3") {
	  if ((status1 == 'none')) {
		  showhide(id1);
	  }
	  if ((status2 != 'none')) {
		  showhide(id2);
	  }
	  if ((status3 != 'none')) {
		  showhide(id3);
	  }
	  if ((status4 != 'none')) {
		  showhide(id4);
	  }
  }
  else if (id1 == "vmenu4") {
	  if ((status1 == 'none')) {
		  showhide(id1);
	  }
	  if ((status2 != 'none')) {
		  showhide(id2);
	  }
	  if ((status3 != 'none')) {
		  showhide(id3);
	  }
	  if ((status4 != 'none')) {
		  showhide(id4);
	  }
  }
}

function processAjax(url) {
    

    if (window.XMLHttpRequest) { // Non-IE browsers
      req = new XMLHttpRequest();
      req.onreadystatechange = targetDiv;
      try {
        req.open("GET", url, true);
      } catch (e) {
        alert(e);
      }
      req.send(null);
    } else if (window.ActiveXObject) { // IE
      req = new ActiveXObject("Microsoft.XMLHTTP");
      if (req) {
        req.onreadystatechange = targetDiv;
        req.open("GET", url, true);
        req.send();

      }
    }
  return false;
}

function targetDiv() {
    if (req.readyState == 4) { // Complete
          if (req.status == 200) { // OK response
              document.getElementById("player").innerHTML = req.responseText;
          } else {
            alert("Problem: " + req.statusText);
          }
    }
} 

function show_player(player){
	v=document.getElementById('veoh_tab');
	i=document.getElementById('imeem_tab');
	s=document.getElementById('myspace_tab');
	m=document.getElementById('megavideo_tab');
	o=document.getElementById('other_tab');
	if(v){document.getElementById('veoh').style.display=((player=='veoh')?'block':'none')}
	if(s){document.getElementById('myspace').style.display=((player=='myspace')?'block':'none')}
	if(m){document.getElementById('megavideo').style.display=((player=='megavideo')?'block':'none')}
	if(i){document.getElementById('imeem').style.display=((player=='imeem')?'block':'none')}
	if(o){document.getElementById('other').style.display=((player=='other')?'block':'none')}
	if(v){v.style.backgroundColor=((player=='veoh')?'#505050':'#393939')}
	if(s){s.style.backgroundColor=((player=='myspace')?'#505050':'#393939')}
	if(m){m.style.backgroundColor=((player=='megavideo')?'#505050':'#393939')}
	if(i){i.style.backgroundColor=((player=='imeem')?'#505050':'#393939')}
	if(o){o.style.backgroundColor=((player=='other')?'#505050':'#393939')}
}


function ltrim(str)
{
	return str.replace(/\s*((\S+\s*)*)/g, "$1");
}

function rtrim(str)
{
	return str.replace(/((\s*\S+)*)\s*/g, "$1");
}

function trim(str)
{
	return ltrim(rtrim(str));
}

function checkAll(checkboxes, state)
{
  if (checkboxes.length)
    for (i=0;i<checkboxes.length;i++){
      checkboxes[i].checked = state;
    }
  else
    checkboxes.checked = state;
}

function checkSelection(checkboxes)
{
  if (checkboxes.length)
    for (i=0;i<checkboxes.length;i++){
     if (checkboxes[i].checked)
       return true;
    }
  else
   if (checkboxes.checked)
     return true;

  alert("Please make selection first");
  return false;
}

function confirmDel()
{
  return confirm("Are you sure you want to delete this data?");
}
function confirmFrm()
{
  return confirm("Submitting this form will reaload the page, Continue?");
}

function confirmDelete(currentform, actfield)
{
  if (!actfield)
    actfield = 'mode';

  if (currentform) {
    currentform[actfield].value='del';

    if (confirmDel())
      currentform.submit();
  }
  showLoading();
  return false;
}

function getUrlParam(url, par)
{
  var rgx = "[\\?&]"+par+"=([^&#]*)";
  var regex = new RegExp(rgx);
  var matches = regex.exec(url);

  return (matches == null)? "" : matches[1];
}

function submitForm(frm, btn, text)
{
  if (btn) {
    btn.disabled = true;
    btn.value = text;
  }
  frm.submit();
}

function changeWidgetCode(wtype)
{
  var newcode = $('#widget_code').val();
  var w = $('#widget_width').val();
  var h = $('#widget_height').val();

  if (wtype == 1) {
    newcode = newcode.replace(/videowidget.*?\.swf/, "videowidget.swf");
    newcode = newcode.replace(/width=".*?"/, "width=\""+w+"\"");
    newcode = newcode.replace(/height=".*?"/, "height=\""+h+"\"");
  } else {
    newcode = newcode.replace(/videowidget.*?\.swf/, "videowidget_s.swf");
    newcode = newcode.replace(/width=".*?"/, "width=\"380\"");
    newcode = newcode.replace(/height=".*?"/, "height=\"285\"");
  }

  $('#widget_code').val(newcode);
  var embed_regex = new RegExp(/<embed.*<\/embed>/);
  var embed_code = embed_regex.exec(newcode);

  if (embed_code)
  {
    $('#embed_code').html(embed_code[0]);
  }
  showLoading();
  return false;
}

function getVideoInfo(videourl)
{
  if (videourl.value == '') {
    alert('Please enter video url');
    return false;
  }

  oldbuttonval = $('#getvideo').val();
  $('#getvideo').val('Retrieving info...').attr({'disabled': 'disabled'});
  $.post('getvideoinfo.php',
         {'url' : videourl.value},
         function(json) {
           $('#getvideo').val(oldbuttonval).removeAttr('disabled');
           result = eval('('+json+')');
           if (result.returnval != 1) {
             $('#getinfomsg').html(result.returnmsg).slideDown('slow').animate({opacity:1}, 7000).slideUp('slow');
           } else {
             $('#title').val(result.title);
             $('#thumbnail_url').val(result.thumbnail);
             $('#description').val(result.description);
             $('#tags').val(result.tags);
             $('#embed_code').val(result.embed_code);
           }
         });
		 showLoading();
  return false;
}

function addComment(frm)
{
  $('#cmt_msg').slideUp();
  var oldbuttonval = $('#addcomment').val();
  $('#addcomment').val('Adding comment...').attr({'disabled': 'disabled'});
  $.post(IVIDPLAY_BASE_DIR+'comment/add.php',
         {'ajax' : '1',
          'timestamp' : frm.timestamp.value,
          'video_id' : frm.video_id.value,
          'name' : frm.name.value,
          'comment' : frm.comment.value,
		  'touringcode' : frm.touringcode.value,
		  'user_id' : frm.user_id.value,
		  'type' : frm.type.value},
         function(json) {
           $('#addcomment').val(oldbuttonval).removeAttr('disabled');
           var result = eval('('+json+')');
           if (result.returnval != 1) {
             $('#cmt_msg').html(result.returnmsg).slideDown();
           } else {
             frm.reset();
             $('#cmt_nocomment').remove();
             if (getUrlParam($('#link_newer').attr('href'), 'cst') == '1') 
			 {
               $('.cmt_nav').css({'display': 'block', 'visibility': 'visible'});
			   $('#cmt_msg').html(result.returnmsg).slideDown();
			   document.getElementById('botcheck').src = document.getElementById('botcheck').src + '#';
               loadComments($('#link_newer'));
             } else {
               var url = $('#link_newer').attr('href').replace(/cst=\d+/, 'cst=1');
               $('#link_newer').attr({'href' : url});
			   $('#cmt_msg').html(result.returnmsg).slideDown();
			   document.getElementById('botcheck').src = document.getElementById('botcheck').src + '#';
               url = $('#link_older').attr('href').replace(/cst=\d+/, 'cst=1');
               $('#link_older').attr({'href' : url});
               loadComments($('#link_newer'), 'reload');
             }
           }
         });
  showLoading();
  return false;
}

function loadComments(obj, getcmt, getid) {
    var params = $(obj).attr('href').split('?');
	if (params == '')
	{
		params = getid;
	}
    $.getJSON(IVIDPLAY_BASE_DIR+'comment/load.php?'+params[1], function(json) { 
        if (json.returnval == 1) {
			$('#cmt_comments').fadeOut('fast', function() { $(this).html(json.comments).fadeIn('slow'); });
			if (getcmt != 'reload') {
               var url = $('#link_newer').attr('href').replace(/cst=\d+/, 'cst='+json.cst);
               $('#link_newer').attr({'href' : url});
               url = $('#link_older').attr('href').replace(/cst=\d+/, 'cst='+json.cst);
               $('#link_older').attr({'href' : url});
            }
        }
    });
	showLoading();
    return false;
}
function loadThumb(obj, mtype, getid)
{
	var params = $(obj).attr('href').split('?');
	$.getJSON(IVIDPLAY_BASE_DIR+'comment/load_thumb.php?'+params[1], function(json) { 
        if (json.returnval == 1) {
			if (mtype == 'up') 
			{
				$('#cmt_result_'+getid).fadeOut('fast', function() { $(this).html('Thank You for Your Vote!').fadeIn('slow'); });
				$('#thumb_up_'+getid).fadeOut('fast', function() { $(this).html(json.thumb_data).fadeIn('fast'); });
			}
			if (mtype == 'down') 
			{
				$('#cmt_result_'+getid).fadeOut('fast', function() { $(this).html('Thank You for Your Vote!').fadeIn('slow'); });
				$('#thumb_down_'+getid).fadeOut('fast', function() { $(this).html(json.thumb_data).fadeIn('fast'); });
			}
        }
		else if (json.returnval == 0)
		{
			$('#cmt_result_'+getid).fadeOut('fast', function() { $(this).html(json.returnmsg ).fadeIn('slow'); });
		}
    });
	showLoading();
	return false;
}

function loadFlag(getid)
{
	showLoader();
	var flag_reason = document.forms["flag_report"]["flag_reason"].value;
	$.getJSON(IVIDPLAY_BASE_DIR+'comment/load_flag.php?id='+getid+'&reason='+flag_reason, function(json) { 
		if (json.returnval == 1) {
			$('#cmt_result_'+getid).fadeOut('fast', function() { $(this).html('Thank You for Flagging this Comment as Bad!').fadeIn('slow'); });
			triggerFlag(getid);
		}
		else if (json.returnval == 0) {
			$('#cmt_result_'+getid).fadeOut('fast', function() { $(this).html(json.returnmsg).fadeIn('slow'); });
			triggerFlag(getid);
		}
	});
	showLoading();
	return false;
}

function delVideo(href, divid)
{
  if (confirmDel()) {
    var video_id = getUrlParam(href, 'id');
    var token = getUrlParam(href, 'token');
    $('#'+divid).fadeTo('slow', 0.33);
    $.get(IVIDPLAY_BASE_DIR+'ajax/del_video.php?id='+video_id+'&token='+token,
          function(json) {
            var result = eval('('+json+')');
            if (result.returnval == 1) {
              $('#'+divid).fadeOut('slow');
			  $('#cmt_result').fadeOut('fast', function() { $(this).html(result.returnmsg).fadeIn('slow'); showLoading(); });
            } else {
              $('#'+divid).fadeTo('fast', 1, function() { alert(result.returnmsg); });
            }
          });
  }
  showLoading();
  return false;
}

function delPlaylist(href, divid)
{
  if (confirmDel()) {
    var playlist_id = getUrlParam(href, 'id');
    var token = getUrlParam(href, 'token');
    $('#'+divid).fadeTo('slow', 0.33);
    $.get(IVIDPLAY_BASE_DIR+'ajax/del_playlist.php?id='+playlist_id+'&token='+token,
          function(json) {
            var result = eval('('+json+')');
            if (result.returnval == 1) {
              $('#'+divid).fadeOut('slow');
			  $('#cmt_result').fadeOut('fast', function() { $(this).html(result.returnmsg).fadeIn('slow'); showLoading(); });
            } else {
              $('#'+divid).fadeTo('fast', 1, function() { alert(result.returnmsg); });
            }
          });
  }
  showLoading();
  return false;
}

function reportInappropriate(id, uid, reason)
{
	if (reason == "") {
		alert('Please choose your reason..');	
		return false;
	}
	if (id != "") {
		var report = confirm("Are you sure want to report this video as inappropriate ??");
		if (report) {
			$.get(IVIDPLAY_BASE_DIR + 'ajax/report_video.php?mode=r_inappropriate&id=' + id + '&uid=' + uid + '&reason=' + reason);
			$('#inappropriate_flag').html('Thank you for reporting this video');
			$('#inappropriate').toggle();
		}
	}
	showLoading();
}

function reportLink(id, uid, url)
{
	if (url != "") {
		$.get(IVIDPLAY_BASE_DIR + 'ajax/report_video.php?mode=r_brokenlink&id=' + id + '&uid=' + uid + '&url=' + url);
	}
	else {
		$.get(IVIDPLAY_BASE_DIR + 'ajax/report_video.php?mode=r_brokenlink&id=' + id);
	}
	$('#broken_link').hide();
	$('#report_broken_link').html('Thank you for reporting this video');
	showLoading();
}
function follower(follower_id)
{
  if (!follower_id)
  {
    window.open('http://www.chmava.com/follower/', '', 'width=620,height=700,scrollbars=yes')
  }
  else
  {
    window.open('http://www.chmava.com/follower/'+follower_id, '', 'width=620,height=700,scrollbars=yes')
  }
}

function triggerReply(c_id)
{
	$('#reply_'+c_id).toggle();
}
function triggerFlag(c_id)
{
	$('#flag_report_'+c_id).toggle();
}
function triggerReps(c_id)
{
	$('#reps_'+c_id).toggle();
}
function triggerFriends(c_id)
{
	$('#friend_request_'+c_id).toggle();
}
function triggerContent(s_id, c_id)
{
	$('#'+s_id+'_'+c_id).toggle();
}
function checkForms(elem, msg, uid, mom, type)
{
  showLoader();
  $('#cmt_result_'+uid).fadeOut();
  if(elem.value.length == 0){ $('#cmt_result_'+uid).fadeOut('fast', function() { $(this).html(msg).fadeIn('slow'); }); showLoading(); return false; }
  else{ if(type == 1){ triggerContent(mom, uid); document.forms["form_"+uid].submit(); } if(type == 3){ document.forms["form_"+uid].submit(); }}
}
function checkForms(elem, msg, uid, mom, type)
{
  showLoader();
  $('#cmt_result_'+uid).fadeOut();
  if(elem.value.length == 0){ $('#cmt_result_'+uid).fadeOut('fast', function() { $(this).html(msg).fadeIn('slow'); }); showLoading(); return false; }
  else{ if(type == 1){ if(confirmFrm()){ triggerContent(mom, uid); document.forms["form_"+uid].submit(); } } if(type == 3){ document.forms["form_"+uid].submit(); }}
}
