var serverURL='';
messages = new Array("Rate this content:", "Useless!", "Poor", "Fair...", "Nice", "Awesome!");

function showStars(starNum,varID)	
{	       
		varID =  '_' + varID ; 			
		if(starNum > 5) starNum =5;
		for(i=1;i<=starNum;i++)
			document.getElementById("star__"+i+varID).src = "/images/icn_star_full_19x20.png";
		for(i=starNum + 1;i<=5;i++)
			document.getElementById("star__"+i+varID).src = "/images/icn_star_empty_19x20.png";
		document.getElementById("ratingMessage"+varID).innerHTML = this.messages[starNum];
}

function clearStars(starNum,varID)
{
	varID =  '_' + varID ;
	curRat = document.getElementById("currentRating"+varID).value;
	if(curRat > 5) curRat =5;
	for(i=1;i<=5;i++)
	{
		if(i>curRat)
			document.getElementById("star__"+i+varID).src = "/images/icn_star_empty_19x20.png";
		else
			document.getElementById("star__"+i+varID).src = "/images/icn_star_full_19x20.png";
	}
	document.getElementById("ratingMessage"+varID).innerHTML = this.messages[curRat];
}

function setStars(starNum,varID,hid)
{
	var varID_N;
	varID_N = varID ;
	varID =  '_' + varID ; 
		
		for(i=1;i<=starNum;i++)
		document.getElementById("star__"+i+varID).src = "/images/icn_star_full_19x20.png";
		document.getElementById("currentRating"+varID).value = starNum;
		document.getElementById("ratingMessage"+varID).innerHTML = this.messages[starNum];
		rateThis(starNum,varID_N,hid) ;
}

function rateThis(rating,varID,hid){
	sess_id = GetuserId();
	if (sess_id == '') 	{
		alert ("Only active users may rate content, please login now.") ;
	}
	else	{
		var url = 'FlagItem.php';
		//h_ids =  document.getElementById('Item_id').value;
		document.getElementById('varid').value = varID;
		var pars ="act=rated&history_id="+hid+"&sess_id="+sess_id+"&rating="+rating;
		var target = '';
		var myAjax = new Ajax.Updater(target, url, {method: 'get', parameters: pars, onComplete: showResponse})
	}
}

function GetuserId()
{
	var sess_id = document.getElementById('sess_id').value;
	return sess_id;
}

function AddCommentToItem(id)
{
  getMouseXYN(); 
  var ids=document.getElementById('del_HL');
  document.getElementById('h_lids').value = id;
  document.getElementById('comments').value="";
  ids.style.left = mousexN+5+'px';
  ids.style.top =  mouseyN+5+'px';
  ids.style.visibility = "visible";
}

function showMore(id)
{
   var more = document.getElementById('more_'+id);
   more.style.display = 'block';
   var morelink= document.getElementById('morelink_'+id);
   morelink.style.visibility = 'hidden';
}

function contentItemMouseOver(elem,id)
{
  var chbx = document.getElementById('checkbox_id_'+id);
  if(!chbx.checked)
    elem.className = 'contnet_all-hover';	
}

function contentItemMouseOut(elem,id)
{
  var chbx = document.getElementById('checkbox_id_'+id);
  if(!chbx.checked)  
	elem.className = 'contnet_all';
  else
    elem.className = 'contnet_all_marked';	
}

function switchChecked(e, id)
{
	var elem = (e.target) ? (e.target) : e.srcElement;
    if(elem.tagName == "A" || elem.tagName == "IMG") return;
    var checkbox = document.getElementById('checkbox_id_'+id);
    var content_item = document.getElementById('contnet_all_'+id);
      
    if(checkbox.checked) 
    {
	  content_item.className = 'contnet_all';   
      checkbox.checked = false;	
    }
    else
    {
	  content_item.className = 'contnet_all_marked';	
      checkbox.checked = true;
    }

}

function showLess(id)
{
  var more = document.getElementById('more_'+id);
  more.style.display = 'none';
  var morelink= document.getElementById('morelink_'+id);
   morelink.style.visibility = 'visible';
}

function contentMouseHover()
{
   var id = document.getElementById('contentblock').value;
   var arr = id.split('_');
   var id = arr[2];
   var elem = document.getElementById('content_block_'+id);
   elem.className = 'content_block-hover';
}

function contentMouseOut()
{
   var id = document.getElementById('contentblock').value;
   var arr = id.split('_');
   var id = arr[2];   
   var elem = document.getElementById('content_block_'+id);
   elem.className = 'content_block-hover';
}

function findPosX(obj)
{
  var curleft = 0;
  if(obj.offsetParent)
    while(1) 
    {
      curleft += obj.offsetLeft;
      if(!obj.offsetParent)
        break;
      obj = obj.offsetParent;
    }
  else if(obj.x)
    curleft += obj.x;
  return curleft;
}

function findPosY(obj)
{
  var curtop = 0;
  if(obj.offsetParent)
    while(1)
    {
      curtop += obj.offsetTop;
      if(!obj.offsetParent)
        break;
      obj = obj.offsetParent;
    }
  else if(obj.y)
    curtop += obj.y;
  return curtop;
}

function ShowMailWnd(id, hid)
{	
    document.getElementById('sendmail_btn').className = 'send';
	document.getElementById('sendmail_btn').innerHTML = 'send';
	document.getElementById('sendmail_btn').title = 'send';
	document.getElementById('h_lids').value = id;
	document.getElementById('h_id').value = hid; 
    var sm=$id('SendMail_wnd');
	getMouseXYN(); 
    sm.style.left = mousexN-375+'px';
	sm.style.top =  mouseyN-175+'px';
    sm.style.display='inline';
    sm.style.visibility = "visible";	
	sm.focus();
}

function CloseMail() 
{
    $id('SendMail_wnd').style.display='none';
}


function ShowEditWnd(id, hid)
{
	document.getElementById('edit_sc').className = 'send';
    var elem = document.getElementById('linktohl_'+id);
    var old = elem.value; 
	var index = old.lastIndexOf('/');
	var edit = old.substr(index+1);
	var nonedit = old.substr(0,index+1);

	document.getElementById('oldurl').innerHTML = nonedit;
	document.getElementById('oldurl').style.width = 'auto';
	document.getElementById('newurl').value = edit;
	document.getElementById('oldscid').value = id;

    var sm=$id('Edit_wnd');	
    sm.style.left = findPosX(elem)+'px';
	sm.style.top =  findPosY(elem)-70+'px';
    sm.style.display='inline';
    sm.style.visibility = "visible";	
	sm.focus();
	$id('newurl').select() ;	//Added by RC on 09/03/08
}

function ClosePersonalize() 
{
    $id('Personalize_wnd').style.display='none';
}


function showPersonalize(id)
{ 
    var elem = document.getElementById('linktohl_'+id);
	var sm=$id('Personalize_wnd');	
    sm.style.left = findPosX(elem)+20+'px';
	sm.style.top =  findPosY(elem)-80+'px';
    sm.style.display='inline';
    sm.style.visibility = "visible";	
	sm.focus();
}

function containsWS(edit)
{
  var pos = edit.indexOf(' ');

  if(pos <= edit.length-1 && pos >=0) return true; else return false;
}
function copyUrl()
{
	var id = document.getElementById('oldscid').value;
	var elem = document.getElementById('linktohl_'+id);
    var old = elem.value; 
	if( window.clipboardData && clipboardData.setData )
	{
	  if(clipboardData.setData("text", old))
	  {
	    alert("The URL has been copied!");
	  }
	}
	else
	{
	  alert("Internet Explorer required");
	}
	$id('edit_copy').className='send';
	$id('Edit_wnd').style.display='none';
}
function changevnt(newid)
{   
	self.location.href = newid;
}
function saveUrl()
{
	var id = document.getElementById('oldscid').value;
	var second = document.getElementById('newurl').value;
	var elem = document.getElementById('linktohl_'+id);
	var lnk = document.getElementById('ct_'+id);
	var logoref=document.getElementById('logo_'+id);
    var old = elem.value; 
	var index = old.lastIndexOf('/');
	var edit = old.substr(index+1);
	var nonedit = old.substr(0,index+1);
	second = second.trim();
	
	if(!second)
    {
	  alert("This field can not be empty.");
	  CloseEdit();
	  return false;
	}
	if(containsWS(second)) { alert('Whitespace not allowed in URL.'); CloseEdit(); return false; }
	if(second == edit) { alert('No change has been made.'); CloseEdit(); return false; }
	
	var url = 'Checksc.php';	  
	var pars= "id="+edit+"&val="+second+"&task=updatesc";
    var target = '';	
	
    new Ajax.Request(url,
    {
      method:'get',
	  parameters: pars,
      onSuccess: function(transport){
        var response = transport.responseText || "no response text";		
        if(response == 'success') {  CloseEdit(); var newsc = nonedit+""+second; elem.value = newsc; lnk.href=newsc; lnk.innerHTML=newsc; logoref.onclick= function(){changevnt(newsc);}; alert("The tiny URL to these highlights has been personalized for you."); //we shud suggest he email it now!! 
	    }
		else if(response == 'dp') {  CloseEdit(); alert('Sorry that URL already exists.\r\nPlease try again.'); return false;}
	    else { CloseEdit(); alert('Invalid url, please try again with a different name'); return false;}
      },
      onFailure: function(){ alert('Something went wrong...\r\nPlease try again.'); return false }
    });
}
function CloseEdit() 
{
    $id('Edit_wnd').style.display='none';
}


function disableSend()
{
    document.getElementById('sendmail_btn').className = 'send_disabled';     
}

function ChangeMailAll()
{
    var st=$id('SendMailToAll').checked;
    var pm = document.getElementById('populate_mails');
	var elems = pm.getElementsByTagName('input');
    for(var i=0;i<elems.length;i++) elems[i].checked=st;
}

var mousexN = 0;
var mouseyN = 0;
document.onmousemove = getMouseXYN;

function getMouseXYN(e) 
{ 
  if (!e) e = window.event; 
  
  if (e)
  { 
  if (e.pageX || e.pageY)
  { 
  mousexN = e.pageX;
  mouseyN = e.pageY;
  }
  else if (e.clientX || e.clientY)
  { 
  mousexN = e.clientX + document.documentElement.scrollLeft;
  mouseyN = e.clientY + document.documentElement.scrollTop;
  }  
 }
}

function $id(ob)
{
    	return document.getElementById(ob);
}

function hide_mob()
{
	var ids=document.getElementById('del_HL');
	ids.style.visibility = "hidden";
}

function $class(ob, parent)
{
    var par=document.body;
    if(parent!=null) par=parent;
    var children = par.getElementsByTagName('*');
    var v=[];
    for(var a=0;a<children.length;a++) if(children[a].className==ob) v[v.length]=children[a];
    return v;
}

function getHighliteId(content_id) 
{
    var content = document.getElementById('content_'+content_id);
	var rows = content.getElementsByTagName('input');
    var recent = 0;
	
	for(var i=0; i < rows.length; i++) 
	{
	  if(rows[i].type == "checkbox") 
	  {
		recent = (recent < rows[i].value) ? rows[i].value : recent;  
	    if(rows[i].checked) 
		{
		  	return rows[i].value;
		}			
	  }
	}
	
	return recent;
}

function FlagAsNotUseful(id,action)
{    
	var url = 'FlagItem.php';	
	var sess_id = GetuserId();
	var pars ="act=add&hl_id="+id+"&sess_id="+sess_id;
	var target = '';
	var myAjax = new Ajax.Updater(target, url, {method: 'post', parameters: pars, onComplete: showResponse})
}

function addEmailComment(hl_id,comment,private)
{
  	var url = 'FlagComment.php';
	var hilite_id = getHighliteId(hl_id);
	var commentid="content_item_comment_" + hilite_id;

	if(document.getElementById(commentid)!==null)
	{
		var fchild=document.getElementById(commentid);
		fchild.innerHTML = '' ; 
		var str1 = "";				       
	}
	var sess_id = GetuserId();
	var pars ="act=add&hl_id="+hilite_id+"&sess_id="+sess_id+"&comments="+comment+"&private="+private;
	var target = '';
	var myAjax = new Ajax.Updater(target, url, {method: 'post', parameters: pars,onComplete: showResponse});
}

function PrintPageNew(shid)
{
  window.open(serverURL+'india_art.php?print=true&shid='+shid);
}

function PrintPage(history_id)
{
  window.open(serverURL+'india_art.php?print_id='+history_id);
}

function SendMail() 
{   
	var email_adresses=$id('mail_data').value;   
    var all=$id('SendMailToAll').checked;
    var emails=$class('smallcheck');
    var comment = $('mail_data').value;	
	var subject = $('subject').value;
    var private = ($('private').checked) ? 1 : 0; 
	var sess_id = GetuserId();
	
	if(sess_id =="" && private)
	{
		alert("You should signin before adding private comments.");
		return;
	}
	var hl_id = document.getElementById('h_lids').value;
	var history_id = document.getElementById('h_id').value;
	if(comment.length) addEmailComment(hl_id,comment,private);    
	email_adresses = $id('mail_to').value ;
    for(var i=0;i<emails.length;i++)
        if(all || emails[i].checked) email_adresses+=','+emails[i].value;		
    if(email_adresses.charAt(0)==',') email_adresses=email_adresses.substring(1);
	var pars = 'history_id='+history_id+'&hl_id='+hl_id+'&private='+private+'&comment='+comment+'&subject='+subject+'&from='+$id('mail_to').innerHTML+'&adr='+email_adresses;
    var myAjax = new Ajax.Updater('','SendMailFunction.php', {method: 'post', parameters: pars, onComplete: function (transport) { CloseMail(); alert(transport.responseText);}});  
   
}

function Add_user_comments()
{
	var url = 'FlagComment.php';
	idss = document.getElementById('h_lids').value;
	var ucomments = document.getElementById('comments').value;
	var commentid="content_item_comment_" + idss;	
	var private = (document.getElementById('private_check').checked) ? 1 : 0;
	var sess_id = GetuserId();
	
	if(sess_id =="" && private)
	{
		alert("You should signin before adding private comments.");
		return;
	}
	var str1="";	
	
	if(document.getElementById(commentid)!==null)
	{
		var fchild = document.getElementById(commentid);
		//fchild.innerHTML = '' ;				
        str1="<div class=\"content_item_comment\"><span class=\"content_item_flag_comm\"><img id=\"content_item_flag_"+ idss +"\" src=\"/images/sflag.gif\" alt=\"Flag as inapropriate, spam\" title=\"Flag as inapropriate, spam\"></span><div class=\"content_item_description_empty\" id=\"content_item_comment_"+ idss +"\"><a href=\"javascript:AddCommentToItem('"+ idss +"')\">Add Comments</a></div><div class=\"content_item_description\"><font color=\"Green\">"+ucomments+"</font></div></div>";	
//fchild.innerHTML = str1 ; 		
	}		

	var pars ="act=add&hl_id="+idss+"&sess_id="+sess_id+"&comments="+ucomments+"&private="+private;

	var target = '';
	var myAjax = new Ajax.Updater(target, url, {method: 'post', parameters: pars, onComplete: showResponse});
}

function showResponse(originalRequest)
{
	var RText="";
	var flag = true;
	var response = originalRequest.responseText.trim();

	if(response.indexOf("~!")!=-1)
	{
	  var contensplit =response.split("~!");
	  
      if(contensplit[0]=="cdone")
      { 	    
		
		hide_mob();
		//RText="";
		flag = false
		var fchild = document.getElementById("commentblock_"+contensplit[1]);		
		fchild.innerHTML = '';
		//alert(fchild.id);
		fchild.innerHTML = contensplit[2];
		return;
		//alert("Comments added successfully.");
	  }
	  else if(contensplit[0] == "duplicate")
	  {
		//alert("Duplicate comments are not allowed");  
		return false;
	  }
	}
	else if(response.indexOf(":")!=-1)
	{		
		var contensplit =response.split(":");
		RText = contensplit[0];
		if(RText!="")
		{
			RText1 = RText.split("~");
			
			if(RText1[1]=="yes")
			{
              if (confirm( RText1[0]+"\n"+"Do you want to restore other deleted items?" ))
  			  {
				SavetoMylites("undohl");				
 			  }
			}
			else
			{
			  alert(RText);
			}
	    }
	    contnet_item_flags = "content_item_flag"+contensplit[1];
	    document.getElementById("content_item_flag"+contensplit[1]).style.visibility='hidden';
		flag = false;
    } 
	else if(response.indexOf("#") != -1)
	{
	  var arr = response.split("#");	
	  response = arr[0];
	}
	
	if(response=="done")
	{
	  showAlert(2000, "Comments added successfully.");
	} 
	else if(response=="fail")
	{
	  alert("Oops, an error occured while adding your comments. \r\nPlease try again.");
      hide_mob();
	}
	else if(response=="unknownuser")
	{
	  alert("Please signin to make comments.");
	  hide_mob();
	} 
	else if(response=="Copy")
	{
		showAlert(2000,"Your Highlights have been saved.");
	}
	else if(response=="mfav")
	{
		showAlert(2500,"The selected Highlights have been saved to your Favorites.");
	}
    else if(response=="foadd")
	{
		showAlert(2000,"The Highlights have been added.");
	}
	else if(response=="Deleted")
	{
		DisabledHl();
		var delmessage = "Selected Hilights have been moved to trash";        
	}
	else if(response=="undo_done")
	{
      UndoHl();     
	}
	else if(response=="ratd")
	{
		//alert("Thank you for rating it - we sincerely appreciate your ratings.");
		showAlert(2000, "Thank you for rating it - we sincerely appreciate your ratings.");
		var varid = document.getElementById('varid').value;		
		//document.getElementById('rating_'+varid).innerHTML = arr[2]+"rating "+arr[1]+" stars ";
		document.getElementById('rating_'+varid).innerHTML = arr[2]+" ratings ";
		
	}
	else if(response=="ratefailed")
	{
		alert("I am afraid I was not able to rate this page for you.");
	}
    else if(response=="50")
	{
		showAlert(3000,"<strong>Success</strong>: marked as PRIVATE.");
	}
    else if(response=="1")
	{
		showAlert(3000,"<strong>Success</strong>: marked as PUBLIC.");
	}
    else if(response=="pvtFailure")
	{
		showAlert(3000,"You can only mark your own Highlights as Public/Private.");
	}
	else if(flag)
	{
	   alert(response);	
	}
}


function DisabledHl()
{
    var items=$startsWith('checkbox_id_',$id('main_menu')); 
    for(var a=0;a<items.length;a++)
    {
        var ob=$id('content_item_'+items[a].id.substring(12));
        if(items[a].checked && ob.style.display!='none') 
        {
             ob.style.visibility = "hidden";
        }
	}
	return "done";
}

function CheckAllChange(e)
{
    var kako=$id('inputTHMB').checked;   
    var items=$startsWith('checkbox_id_',$id('main_menu'));
    for(var a=0;a<items.length;a++)
	{
	  var id = items[a].id;
	  $arr = id.split('_');
	  if(items[a].checked == kako) continue;
	  switchChecked(e, $arr[2]);
	  items[a].checked=kako;
	}
}

function $startsWith(ob, parent)
{
    var par=document.body;
    if(parent!=null) par=parent;
    var children = par.getElementsByTagName('*');
    var v=[];
    for(var a=0;a<children.length;a++) if(children[a].id.startsWith(ob)) v[v.length]=children[a];
    return v;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function SavetoMylites(task,hid)
{	
	if(!task)
	task="";	
	var h_ids = "";
    var items=$startsWith('checkbox_id_',$id('main_menu'));
	var sess_id = GetuserId();
	
	oneItemAdded = false;
    for(var a=0;a<items.length;a++) 
	{
		if(items[a].checked==true)
		{
			if(true == oneItemAdded)
				h_ids += "," ;
			else
				oneItemAdded = true;
			h_ids = h_ids+items[a].value;
		}
	}

	if(h_ids=="" && task!='musers' && task!='follow')
	{
		alert("Please select some highlights.");
	}
	else
	{	
		if(sess_id=="" && task!='musers')
		{
			alert("Please signin now.");
			return;
		}
		else
		{	
			if(task=="mfav")
			{
				var url = 'FlagItem.php';
				var pars ="act=markFav&hl_id="+h_ids+"&sess_id="+sess_id;
			}
			else if (task =="combineHLs")
			{
				window.location = 'combineHLs.php?formatted=true&list=' + h_ids ;
				exit ;
			}
			else if (task =="markPvt")
			{
				var url  = "/makePvtHL.php" ;
				var pars = "pvt=true&hlid=" + h_ids ;
			}
			else if (task =="markPublic")
			{
				var url  = "/makePvtHL.php" ;
				var pars = "pvt=false&hlid=" + h_ids ;
			}
			else if (task=="delete")
			{
				if (confirm("Are you sure you want to delete?"))
				{
					var now = new Date().getTime();
					var url = 'DeleteHiliteFunction.php?now='+now ;
					document.getElementById('Item_id').value = h_ids;
					document.getElementById('task').value = "delete";
					document.getElementById('sess_id').value = sess_id;
					var pars ="act=delete&Item_id="+h_ids+"&sess_id="+sess_id;
				}
			}
			else if (task=="undohl")
			{
				var now = new Date().getTime();
				var url = 'UndeleteHiliteFunction.php?now='+now ;
				var pars ="act=undohl&Item_id="+h_ids+"&sess_id="+sess_id;
			}
			else if(task=='follow')
			{
				var url = 'FlagItem.php';
				var pars ="act=follow&history_id="+hid+"&sess_id="+sess_id;
			}
			else if(task=="musers")
			{
				document.frm.action = "/site/view1.php?what=moreFu";
				document.getElementById('Item_id').value = hid;
				document.frm.submit();
			}
			else
			{
				var url = 'CopyHilite.php';
				var pars ="act=savelites&hl_id="+h_ids+"&sess_id="+sess_id;
			}

			var target = '';
			var myAjax = new Ajax.Updater(target, url, {method: 'get', parameters: pars, onComplete: showResponse})
		}
	}
}
String.prototype.startsWith=function(s){ return this.indexOf(s)==0; }
String.prototype.trim=function(){ return this.replace(/^\s*|\s*$/g,''); }
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,""); }
