// JavaScript Document



// Subscription functions



favs_on = new Image(175,124) 

favs_on.src = "/images/thumbsup_on.png" 

favs_off = new Image(175,124) 

favs_off.src = "/images/thumbsup_off.png" 

favs_fave = new Image(175,124) 

favs_fave.src = "/images/thumbsup_on.png" 



timerid = 0;



preLoad1 = new Image(331,120) 

preLoad1.src = "/images/thumbsup_on.png" 

preLoad2 = new Image(331,61) 

preLoad2.src = "/images/thumbsup_on.png" 



queueMsqText = "<img width='29' height='28' style='float:left;margin-right:5px;margin-top:2px;' src='/images/queue_msg2.png' align=middle><font size=2>This video was added to your channel. <br />Go to <a href=\"/watch/\">Watch videos</a> to watch it. If you use iTunes, click \"update\" on your Mefeedia channel, then \"get\" to download this video\"</font>";



unqueueMsqText = "<img width='29' height='28' style='float:left;margin-right:5px;margin-top:2px;' src='/images/queue_msg2.png' align=middle><font size=2>This video was removed from your channel</font>";



subscribeMsqText = "<img width='29' height='28' style='float:left;margin-right:5px;margin-top:2px;' src='/images/queue_msg2.png' align=middle><font size=2>You are now subscribed to this feed. <a href=\"/watch/\">Watch Videos</a>.</font>";



unsubscribeMsqText = "<img width='29' height='28' style='float:left;margin-right:5px;margin-top:2px;' src='/images/queue_msg2.png' align=middle><font size=2>You are now unsubscribed from this feed.</font>";



function switchimages(imgDocID,imgObjName){ 

	document[imgDocID].src = eval(imgObjName + ".src"); 

}







function showUnsubscribe(t) 

{

	document.getElementById(t).innerHTML = "<div onclick=\"Unsubscribe("+t+",'/SQ.php');\"><div class=\"btn-22grey\" style=\"float:left\"><span style=\"font-size:10px;\"><a href=\"javascript://\">unsubscribe</a></span></div></div>";

	

	//showUnSubMessage(t, subscribeMsqText);

	

}

function subscribe(feedid,path) 

{

//	alert(""+feedid);

	new Ajax.Request(path, {parameters: '&feedid=' + feedid+'&sq=s' });

	showUnsubscribe(feedid);

}



function showSubscribe(t) 

{

	document.getElementById(t).innerHTML = "<div onclick=\"subscribe("+t+",'/SQ.php');\"><div class=\"btn-22orange\" style=\"float:left\"><span style=\"font-size:10px;\"><a href=\"javascript://\">+ subscribe</a></span></div></div>";

	

	//showSubMessage(t, unsubscribeMsqText);

}

function Unsubscribe(feedid,path) 

{

	//alert(""+feedid);

	new Ajax.Request(path, {parameters: '&feedid=' + feedid+'&sq=s' });

	showSubscribe(feedid);	

	

}



// Queue Functions



function showUnqueue(t) 

{			

	document.getElementById(t).innerHTML = "<a href=\"javascript://\" onclick=\"Unqueue("+t+",'/SQ.php');\"><img src=\"/images/unqueue.gif\" border=0></a>&nbsp;";

	

	//showQueuedMessage(t, queueMsqText);

}

function queue(vid,path) 

{

//	alert(""+vid);

	new Ajax.Request(path, {parameters: '&vid=' + vid+'&sq=q' });

	showUnqueue(vid);

}



function showQueue(t) 

{

	document.getElementById(t).innerHTML = "<a href=\"javascript://\" onclick=\"queue("+t+",'/SQ.php');\"><img src=\"/images/queue.gif\" border=0></a>&nbsp;";	

	

	//showUnQueuedMessage(t, unqueueMsqText);

		

}

function Unqueue(vid,path) 

{

//	alert(""+feedid);

	new Ajax.Request(path, {parameters: '&vid=' + vid+'&sq=q' });

	showQueue(vid);

	

	

}



function showQueuedMessage(vid, theMsg)

{		

	msgTarget = document.getElementById("theQMsg");	

	

	//setup the div for the queued message

	document.getElementById("qmsgText").innerHTML = theMsg;

	document.getElementById("qmsgText").style.padding = "2px 2px 2px 80px";

	

	msgTarget.style.background = "url('/images/que_msg.png') no-repeat";

	msgTarget.style.height = "120px";

	msgTarget.style.top = (getElementPosition(vid).top-22)+"px";		

	msgTarget.style.left = (getElementPosition(vid).left+90)+"px";		

	msgTarget.style.visibility = "visible";				

		

	//clear the timer or the times keeps running on newly shown messages

	clearTimeout(timerid);

	//set the new callback when the time hits

    timerid = setTimeout("document.getElementById('theQMsg').style.visibility = 'hidden';",5000);		

}



function showUnQueuedMessage(vid, theMsg)

{		

	msgTarget = document.getElementById("theQMsg");	

		

	//setup the div for the queued message

	document.getElementById("qmsgText").innerHTML = theMsg;

	document.getElementById("qmsgText").style.padding = "2px 2px 2px 80px";

	

	msgTarget.style.background = "url('/images/small_que_msg.png') no-repeat";

	msgTarget.style.height = "60px"; 

	msgTarget.style.top = (getElementPosition(vid).top-22)+"px";		

	msgTarget.style.left = (getElementPosition(vid).left+90)+"px";		

	msgTarget.style.visibility = "visible";				

		

	//clear the timer or the times keeps running on newly shown messages

	clearTimeout(timerid);

	//set the new callback when the time hits

    timerid = setTimeout("document.getElementById('theQMsg').style.visibility = 'hidden';",5000);		

}



function showSubMessage(vid, theMsg)

{		

	msgTarget = document.getElementById("theQMsg");	

		

	//setup the div for the queued message

	document.getElementById("qmsgText").innerHTML = theMsg;

	document.getElementById("qmsgText").style.padding = "2px 2px 2px 10px";

		

	msgTarget.style.background = "url('/images/small_que_msg_top.png') no-repeat";

	msgTarget.style.height = "100px"; 

	msgTarget.style.top = (getElementPosition(vid).top-105)+"px";		

	msgTarget.style.left = (getElementPosition(vid).left-50)+"px";		

	msgTarget.style.visibility = "visible";				

		

	//clear the timer or the times keeps running on newly shown messages

	clearTimeout(timerid);

	//set the new callback when the time hits

    timerid = setTimeout("document.getElementById('theQMsg').style.visibility = 'hidden';",5000);			

}



function showUnSubMessage(vid, theMsg)

{		

	msgTarget = document.getElementById("theQMsg");	

		

	//setup the div for the queued message

	document.getElementById("qmsgText").innerHTML = theMsg;

	document.getElementById("qmsgText").style.padding = "2px 2px 2px 10px";

	

	// msgTarget.style.background = "url('/images/que_msg_top.png') no-repeat";

	msgTarget.style.background = "url('/images/small_que_msg_top.png') no-repeat";

	msgTarget.style.height = "100px"; 

	msgTarget.style.top = (getElementPosition(vid).top-105)+"px";		

	msgTarget.style.left = (getElementPosition(vid).left-50)+"px";		

	msgTarget.style.visibility = "visible";				

		

	//clear the timer or the times keeps running on newly shown messages

	clearTimeout(timerid);

	//set the new callback when the time hits

    timerid = setTimeout("document.getElementById('theQMsg').style.visibility = 'hidden';",5000);		

}



function getElementPosition(elemID){

	

 	var offsetTrail = document.getElementById(elemID);

 	var offsetLeft = 0;

 	var offsetTop = 0;

 	

 	while (offsetTrail){

  		offsetLeft += offsetTrail.offsetLeft;

  		offsetTop += offsetTrail.offsetTop;

  		offsetTrail = offsetTrail.offsetParent;

 	}

 	

 	if (navigator.userAgent.indexOf('Mac') != -1 && typeof document.body.leftMargin != 'undefined'){

  		offsetLeft += document.body.leftMargin;

  		offsetTop += document.body.topMargin;

 	}

 	return {left:offsetLeft,top:offsetTop};

} 



////////////////////////////////////////////////////////////////

// To implement the favorite tags stuff



function addtofavouritelist(vid,path)

{	

	try
	{	  								

//	new Ajax.Request(path, {parameters: '&vid=' + vid + '&sq=f' });

		//this can be done better via formserialize I think
		pars = 'vid=' + vid
					 + '&sq=f'
					 ;
					
	//alert ('addtoFav AJAX path = ' + path + ' with params = ' + pars + ' .');

//make a call to get data
	  	var addToFavs_myAjax = new Ajax.Request(
			path, 
			{
				method: 'get', 
				parameters: pars, 			
				onComplete: function(retVal) {
					//alert("oncomplete with retval of:" + retVal);
	        		//var resp=retVal.responseText;
					//alert (' response is ' + resp);

					showStar(vid,path,"on");
					return true;
				}
			}
		);		

	//showStar(vid,path,"on");
	}
	catch (err)
	{
	   alert("addtoFavs:"+err+"\n"+err.number+" - "+err.description);
	}

}



function removefromfavouritelist(vid,path){

   

	new Ajax.Request(path, {parameters: '&vid=' + vid + '&sq=rf' });

	showStar(vid,path,"off");

}

	

	

function showStar(vid,path,status) 

{

	if(status=="on"){

	t=vid+"f";

	document.getElementById(t).innerHTML = "<a href=\"javascript://\" onclick=\"removefromfavouritelist("+vid+",'"+path+"');\"><img src=\"/images/thumbsup_on.png\" border=0></a>";

	}

	

	else if(status=="off"){

		

		t=vid+"f";

	    document.getElementById(t).innerHTML = "<a href=\"javascript://\" onclick=\"addtofavouritelist("+vid+",'"+path+"');\"><img src=\"/images/thumbsup_off.png\" border=0></a>";

		

	}

	

}

//////////////////////////////////////////////////////////////////////////



function addtofavouritelist_w(vid,path)

{	

   

	new Ajax.Request(path, {parameters: '&vid=' + vid + '&sq=f' });	

	showStar_w(vid,path,"on");

}



function removefromfavouritelist_w(vid,path){

   

	new Ajax.Request(path, {parameters: '&vid=' + vid + '&sq=rf' });

	showStar_w(vid,path,"off");

}

	

	

function showStar_w(vid,path,status) 

{

	if(status=="on"){

	var t=vid+"f";

	document.getElementById(t).innerHTML = "<a href=\"javascript://\" onclick=\"removefromfavouritelist_w("+vid+",'"+path+"');\" onmouseover=\"switchimages('favs','favs_on');\" onmouseout=\"switchimages('favs','favs_fave');\" ><img name=\"favs\" src=\"/images/favs_fave.png\" border=0></a>";

	}

	

	else if(status=="off"){	

	 var t=vid+"f";

	    document.getElementById(t).innerHTML = "<a href=\"javascript://\" onclick=\"addtofavouritelist_w("+vid+",'"+path+"');\" onmouseover=\"switchimages('favs','favs_on');\" onmouseout=\"switchimages('favs','favs_off');\" ><img name=\"favs\" src=\"/images/favs_off.png\" border=0></a>";

		

	}

	

}

// JavaScript Document

function toggle_description(obj) {
	var el = document.getElementById(obj);

	if ( el.style.visibility != 'hidden' ) {
		el.style.visibility = 'hidden';
	}
	else {
		el.style.visibility = '';
	}
}

var nbsp = 160;		// non-breaking space char
var node_text = 3;	// DOM text node-type
var emptyString = /^\s*$/ ;
var global_valfield;	// retain valfield for timer thread

// --------------------------------------------
//                  trim
// Trim leading/trailing whitespace off string
// --------------------------------------------

function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '');
}


// --------------------------------------------
//                  setfocus
// Delayed focus setting to get around IE bug
// --------------------------------------------

function setFocusDelayed()
{
  global_valfield.focus();
}

function setfocus(valfield)
{
  // save valfield in global variable so value retained when routine exits
  global_valfield = valfield;
  setTimeout( 'setFocusDelayed()', 100 );
}


// --------------------------------------------
//                  msg
// Display warn/error message in HTML element.
// commonCheck routine must have previously been called
// --------------------------------------------

function msg(fld,     // id of element to display message in
             msgtype, // class to give element ("warn" or "error")
             message) // string to display
{
  // setting an empty string can give problems if later set to a 
  // non-empty string, so ensure a space present. (For Mozilla and Opera one could 
  // simply use a space, but IE demands something more, like a non-breaking space.)
  var dispmessage;
  if (emptyString.test(message)) 
    dispmessage = String.fromCharCode(nbsp);    
  else  
    dispmessage = message;

  var elem = document.getElementById(fld);
  elem.firstChild.nodeValue = dispmessage;  
  
  elem.className = msgtype;   // set the CSS class to adjust appearance of message
}

// --------------------------------------------
//            commonCheck
// Common code for all validation routines to:
// (a) check for older / less-equipped browsers
// (b) check if empty fields are required
// Returns true (validation passed), 
//         false (validation failed) or 
//         proceed (don't know yet)
// --------------------------------------------

var proceed = 2;  

function commonCheck    (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  if (!document.getElementById) 
    return true;  // not available on this browser - leave validation to the server
  var elem = document.getElementById(infofield);
  if (!elem.firstChild) return true;  // not available on this browser 
  if (elem.firstChild.nodeType != node_text) return true;  // infofield is wrong type of node  

  if (emptyString.test(valfield.value)) {
    if (required) {
      msg (infofield, "error", "Required field - please enter a value.");  
      setfocus(valfield);
      return false;
    }
    else {
      msg (infofield, "warn", "");   // OK
      return true;  
    }
  }
  return proceed;
}

// --------------------------------------------
//            validatePresent
// Validate if something has been entered
// Returns true if so 
// --------------------------------------------

function validatePresent(valfield,   // element to be validated
                         infofield ) // id of element to receive info/error msg
{
  var stat = commonCheck (valfield, infofield, true);
  if (stat != proceed) return stat;

  msg (infofield, "warn", "");  
  return true;
}

// --------------------------------------------
//               validateEmail
// Validate if e-mail address
// Returns true if so (and also if could not be executed because of old browser)
// --------------------------------------------

function validateEmail  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var stat = commonCheck (valfield, infofield, required);
  if (stat != proceed) return stat;

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/  ;
  if (!email.test(tfld)) {
    msg (infofield, "error", "Not a valid e-mail address");
    setfocus(valfield);
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/  ;
  if (!email2.test(tfld)) 
    msg (infofield, "warn", "Unusual e-mail address - check if correct");
  else
    msg (infofield, "warn", "");
  return true;
}


function validatePasswords  (valfield, valfield2,   // elements to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
	if(valfield.value != valfield2.value){
		msg (infofield, "error", "The two passwords entered do not match.");
		return false;
	}
	else {
		return true;
	}
}


function validateUserName(username,infofield)

{
	//return true;
	var params = "&username=" + username.value + "&sq=u";
	var path = "SQ.php";
	
	//alert ('calling AJAX path = ' + path + ' with params = ' + params + ' .');

	new Ajax.Request(path, {
		method: 'get',
		asynchronous: 'true',
		parameters: params,
		onSuccess: function(retVal) { 
	        var resp=retVal.responseText;
			//alert (' response is' + resp + 'seeing fi there');
			resp = trim(resp);
			if(resp != 'available') {
				msg (infofield, "error", "That username is taken. Please enter another.");
				return false;
			} else {
				//msg (infofield, "", "");
				return true;
			}

		},//retVal; },
		onFailure: handleNoUnique,
		onException: handleNoUnique
	});
	return true;
}

function handleNoUnique()
{	
	alert ('failure of AJAX call');
}

function validateEmailTaken(email,infofield)

{
	//return true;
	var params = "&email=" + email.value + "&sq=uemail";
	var path = "SQ.php";
	//alert ('calling AJAX path = ' + path + ' with params = ' + params + ' .');

	new Ajax.Request(path, {
		method: 'get',
		asynchronous: 'true',
		parameters: params,
		onSuccess: function(retVal) { 
	        var resp=retVal.responseText;
			//alert (' response is ' + resp);
			resp = trim(resp);
			if(resp != 'available') {
				msg (infofield, "error", "There already exists an account using that email address. Maybe you signed up a while ago and forgot?");
			} else {
				//msg (infofield, "warn", "Email looks good.");
				return true;
			}

		},//retVal; },
		onFailure: handleNoUnique,
		onException: handleNoUnique
	});
	return true;
}

function validateURLTaken(friendlyurl,infofield)

{
	//return true;
	var params = "&friendlyurl=" + friendlyurl.value + "&sq=friendlyurl";
	var path = "/SQ.php";
	//alert ('calling AJAX path = ' + path + ' with params = ' + params + ' .');

	new Ajax.Request(path, {
		method: 'get',
		asynchronous: 'true',
		parameters: params,
		onSuccess: function(retVal) { 
	        var resp=retVal.responseText;
			//alert (' response is ' + resp);
			resp = trim(resp);
			//alert ('resp is = ' + resp + ' .');
			if(resp != 'available') {
				msg (infofield, "error", "This URL is already in use - please try another.");
				return false;
			} else {
				msg (infofield, "warn", "URL looks good.");
				return true;
			}

		},//retVal; },
		onFailure: handleNoUnique,
		onException: handleNoUnique
	});
	return true;
}

function showFavsNotLoggedIn(flag, target, movie_id)
{
	try
	{
		//hide for later
		var target_hdn = target+"_hdn";		
		
		toggleBox(target_hdn,1);	//show
		//toggleBox(target,0);		//hide
		
		var theMessage = "<div style=\"border-width:thin; border-style:dashed; border-color:#FF0000; padding-left:2px;\"><span class='lessimportant'><em><b>You need to be logged in to Favorite a video.<b></em><br><br>When you join Mefeedia, faving clips is a great way of collecting videos and allows friends and other users to find cool stuff based on what you favorite!<br><br><em>Please <a href='/sign-in.php?url=/entry/"+movie_id+"/'>login</a> or <a href='/sign-in.php?url=/entry/"+movie_id+"/'>sign up</a></em><br><br></span></div>";
		
		$(target_hdn).innerHTML = theMessage;
		
	}
	catch (err)
	{
	   alert("showFavsNotLoggedIn:"+err+"\n"+err.number+" - "+err.description);
	}

	return;
}
