// JavaScript Document
// Viostream API methods tied to 
//a service handler
// Author: Oliver D'Alton
$(document).ready(function(){
    $("a.fancy-box").fancybox({
      'zoomOpacity'     : true,
      'overlayShow'     : true,
      'zoomSpeedIn'     : 600,
      'zoomSpeedOut'    : 500,
      'easingIn'        : 'easeOutBack',
      'easingOut'       : 'easeInBack',
      'hideOnContentClick': false,
      'callbackOnStart'   : hideFlash,
      'callbackOnClose'   : fnVioClosed,
      'padding'           : 0,
      'overlayOpacity'    : 0.9
    });
  });
  
 var hstryLeng = self.history.length;
  
 function hideFlash(){
    $("#flashcontent").css("visibility", "hidden");
    
  }
  
 function showFlash(){
    $("#flashcontent").css("visibility", "visible");
  }
  
 function fnVioClosed(){
    showFlash();
    $("iframe.videosource").attr("src", "includes/flowplayer.asp");
    setTimeout("fnBackToBegining()",400); //- Seemed to be retriggering the video trapping the user in a loop. Need to investigate further
  }
  
 function fnBackToBegining(){
  var iExtPgs = hstryLeng - self.history.length;
  self.window.history.go(iExtPgs);
 }
  
var bAddingVio = false;
var bInProc = false;



function fnAddViostreamDetails(sVioUID){
	var sReqType = "1";
	var bSuccess = false;
	var bIdSet = true;
	var sHtmlResponse = "";
	
	if(!sVioUID){sVioUID = $("input#vioUID").attr("value");}
	$("input#vioUID").attr("value", "");
		
	if(sVioUID=="" || sVioUID.length != 36){
		alert("You have not specified a valid ID to add to the viostream pool. \nID should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).");
		bIdSet = false;
	}
	
	if(!bAddingVio && bIdSet){
		bAddingVio = true;
		var XMLdoc = fnGetMediaItem(sVioUID);
		bAddingVio = false;
		
		var sVioType = $(XMLdoc).find("MediaBase").attr("MediaType");
		var sVioTitle = $(XMLdoc).find("MediaTitle").text();
		var sVioDesc = $(XMLdoc).find("MediaDescription").text();
		
		if(!sVioType){alert($(XMLdoc).find("Message").text());}
		else{
			bSuccess=true;
			(sVioType.toLowerCase() == "video") ? sVioType = "1" : sVioType = "0";
		}
		
		if(bSuccess){
			sHtmlResponse = fnPostVioProcRequest(sReqType, "", "", "", sVioTitle, sVioDesc, sVioUID, sVioType);
			//alert(sHtmlResponse);
		}
		
	}
	
	$("select#vioselect").prepend(sHtmlResponse);
	
	return true;
}

function fnAttachViostream(sVioID, sContentID){
	var sReqType = "2";
	var bValidRequest = true;
	var sHtmlResponse = "";
	
	if(!sVioID){sVioID = $("select#vioselect option:selected").attr("value");}
	if(!sContentID){sContentID = $("select#exhibselect option:selected").attr("value");}
	if(!sVioID || !sContentID){bValidRequest = false;}
	
	if(bValidRequest){
	 sHtmlResponse = fnPostVioProcRequest(sReqType, sVioID, sContentID, "", "", "", "", "");
	 fnLoadExhibVios(sContentID);
	}
}

function fnRemoveVioFrom(sVioID, sContentID){
	var sReqType = "3";
	var bValidRequest = true;
	
	if(!sVioID){sVioID = $("select#viodisplay option:selected").attr("value");}
	if(!sContentID){sContentID = $("select#exhibselect option:selected").attr("value");}
	if(!sVioID || !sContentID){bValidRequest = false;}
	
	if(bValidRequest){
	 sHtmlResponse = fnPostVioProcRequest(sReqType, sVioID, sContentID, "", "", "", "", "");
	 fnLoadExhibVios(sContentID);
	}
}

function fnDeleteViostream(sVioID){
	var sReqType = "4";

	if(!sVioID){sVioID = $("select#vioselect option:selected").attr("value");}
	if(!sVioID || sVioID == ""){
			alert("You must select a viostream from the pool that you wish to delete.");
	}else{
		var sVioTitle = $("select#vioselect option:selected").text();
		var confResponse = confirm("Are you sure you want to delete this viostream?:\n\n"+ sVioTitle +"\n\nThis will also delete the item from any displays it is attached to...");
		
    if(confResponse){
    
			var sHtmlResponse = fnPostVioProcRequest(sReqType, sVioID, "", "", "", "", "", "");
			alert(sHtmlResponse);
			$("select#vioselect option:selected").remove();
			fnLoadExhibVios();
		}
	}
}

function fnLoadExhibVios(sContentID){
	var sResponseHtml, sReqType, sContentID;
	var bValidRequest = true;
	
	sReqType = "5";
	if(!sContentID){sContentID = $("select#exhibselect option:selected").attr("value");}
	
	if(sContentID){
		sResponseHtml = fnPostVioProcRequest(sReqType, "", sContentID, "", "", "", "", "");
		
		$("#viodisplay").html(sResponseHtml);
	}
}

/*sVioType should be either "video" or "audio"*/
function fnAddSpotlight(sVioID, sVioTitle, sVioDesc, sVioType, sMediaURL){
  
	var sReqType = "7";
	var bValidRequest = true;
	var sHtmlResponse = "";
  var iVioType = 1;
	
	//if(!sVioID){sVioID = $("select#vioselect option:selected").attr("value");}
	if(!sVioTitle){sVioTitle = $("input#vioTitle").attr("value");}
	if(!sVioDesc){sVioDesc = $("textarea#vioDesc").attr("value") + "";}
  if(!sVioType){sVioType = $("input[type=radio]:checked").attr("value");}
  if(!sMediaURL){sMediaURL = $("input#navURL").attr("value");}
  
	if(!sVioTitle || !sVioType || !sMediaURL){bValidRequest = false;}
	
   
	if(bValidRequest){ 
	  if(sVioType == "audio"){ iVioType = 0;}
    
  	//work around to add a custom media URL without refactoring the post function
    sVioType = iVioType  + "&sMediaURL=" + sMediaURL.replace(/&/g, '__and__');
    //--------------------------------------------------------------------------
    
    sHtmlResponse = fnPostVioProcRequest(sReqType, sVioID, "", "", sVioTitle, sVioDesc, "", sVioType);
	}
	else{
		alert("You must enter a title and a URL for the spotlight item.");
	}
	fnSpotlightInput('hide');
	$("select#viospotlight").append(sHtmlResponse);
}

function fnRemoveSpotlight(sVioID){
	var sReqType = "8";
	var bValidRequest = true;
	var sHtmlResponse = "";
	var sVioSpotTitle = $("select#viospotlight option:selected").text();
	if(!sVioID){sVioID = $("select#viospotlight option:selected").attr("value");}
  if(!sVioID){bValidRequest = false;}
  if(bValidRequest){
  	var sConfResponse = confirm("Are you sure you wish to remove the item: \n\n"+ sVioSpotTitle + "\n\n This will remove the details from the homepage.");
  	if(sConfResponse){
  
  		if(!sVioID){bValidRequest = false;}
  		
  		if(bValidRequest){
  			sHtmlResponse = fnPostVioProcRequest(sReqType, sVioID, "", "", "", "", "", "");
  		}
  		
  		if(sHtmlResponse=="success"){
  			$("select#viospotlight option:selected").remove();
  		}
  	}
  }
}

function fnSwapURL(vioUID){
  //height of the player controls, must be set in the iframe asp as well
	var controlHt = 30;
  
	var sMediaXML = fnGetMediaItem(vioUID);
  if(sMediaXML){
  	var sMediaURL, iWidth, iHeight, sVidTitle, sVidText, sImgUrl, bNoWidth;
    bNoWidth = false;
  	// alert(vioUID);
  	//Get the last media URL info usually the High Quality Vid
    
  	$(sMediaXML).find("MediaUrls").each(function(){
  									sMediaURL = $(this).find("Url").eq(0).text();
  									iWidth = parseFloat($(this).find("Width").eq(0).text());
  									iHeight = parseFloat($(this).find("Height").eq(0).text());
  									});
    
    if(!iWidth || iWidth < 400){iWidth = 400; bNoWidth = true}
    if(!iHeight || iHeight < 31){iHeight = 224;}
    
    iHeight = iHeight + controlHt;
    if(bNoWidth){                
      $(sMediaXML).find("Thumbnails").each(function(){
                      $(this).find("Thumbnail").each(function(){
                        var thisWdth = parseFloat($(this).find("Width").text());
                        
                        if(thisWdth == 400){
                          sImgUrl = $(this).find("Path").text();
                        }
                      });
      });
  	}
  	
  	$("#"+vioUID+" iframe.videosource").height(iHeight).width(iWidth);
    
    var sSrcUrl = 'includes/flowplayer.asp?vid='+ sMediaURL +'&h='+ iHeight +'&w='+ iWidth;
  	sSrcUrl = sImgUrl ? sSrcUrl + '&i='+sImgUrl : sSrcUrl;
    
    $("#"+vioUID+" iframe.videosource").attr("src", sSrcUrl);
  	//return 'includes/flowplayer.asp?vid='+ sMediaURL +'&h='+ iHeight +'&w='+ iWidth;
  }else{
    
  }
}

function fnPositionFlowplayer(){}

function fnSpotlightInput(sToggle){
	
	if(sToggle == 'show'){
		$("div#overlay").show();
		$("div#spotlight-info").show();
	}
	else{
		$("div#overlay").hide();
		$("div#spotlight-info").hide();
		$("input#vioTitle").attr("value","");
		$("textarea#vioDesc").attr("value","");
	}
}

function fnPostVioProcRequest(sReqType, sVioID, sContentID, sPriority, sVioTitle, sVioDesc, sVioUID, sVioType){
	if(!bInProc){
		bInProc = true;
		var bValidRequest = false;
		var sHtmlReturn ="";
		
		sVioDesc = escape(sVioDesc);
		sVioTitle = escape(sVioTitle);
		
		bValidRequest = fnValidateProcRequestType(sReqType, sVioID, sContentID, sPriority, sVioTitle, sVioDesc, sVioUID, sVioType);
	 
    
		if(bValidRequest){
		var ProcResponse = $.ajax({
				type: "POST",
				url: "viostream_proc.asp",
				data: "rType="+ sReqType
					+ "&vioID="+ sVioID
					+ "&contID="+ sContentID
					+ "&pri="+ sPriority
					+ "&vioTitle="+ sVioTitle
					+ "&vioDesc="+ sVioDesc
					+ "&vUID="+ sVioUID
					+ "&vType="+ sVioType,
				dataType: "html",
				async: false
			});
		sHtmlReturn = ProcResponse.responseText;
		}else{
			alert("Some information is missing from your request. \n\nRequest was not processed.");
		}
		bInProc = false;
		return sHtmlReturn;
	}
	return "";
}

function fnValidateProcRequestType(sReqType, sVioID, sContentID, sPriority, sVioTitle, sVioDesc, sVioUID, sVioType){
/*1 = add to pool, 2 = associate, 3 = remove association , 4 = delete viostream, 5 = get associated vios, 6 = change spotlight priority 
7 = add to spotlight, 8 = delete from spotlight*/ 	
var bReturn = true;

switch (sReqType){
		case "1":
			if(!sVioUID || !sVioTitle || !sVioDesc || !sVioType){bReturn = false;}
			break;
		case "2":
			if(!sVioID || !sContentID){bReturn = false;}
			break;
		case "3":
			if(!sVioID || !sContentID){bReturn = false;}
			break;
		case "4":
			if(!sVioID){bReturn = false;}
			break;
		case "5":
			if(!sContentID){bReturn = false;}
			break;
		case "6":
			if(!sVioID || !sPriority){bReturn = false;}
			break;	
		case "7":
			if(!sVioTitle || !sVioType){bReturn = false;}
			break;
		case "8":
			if(!sVioID){bReturn = false;}
			break;
		default:
			alert("Invalid request type");
			bReturn = false;
	}

return bReturn;
}

function fnGetMediaItem(vioMediaGetID){
	var sSiteDir = "/";
	var XMLresponse;
	var sHost = window.location.host;
	
	if(sHost == "dev0.deepend.com.au"){sSiteDir = "/mca/site/"}
	
	XMLresponse = $.ajax({
		type: "POST",
		url: "http://"+ sHost + sSiteDir +"access/viostream-service-proxy/viostream-service.asp",
		data: "id_string="+vioMediaGetID
				+"&id_key=mediaId"
				+"&method_name=MediaGet",
		dataType: "xml",
		async: false
	   });
	 
	 var XMLdoc = XMLresponse.responseXML.documentElement;
 
	 return XMLdoc;
}
function fnSearchViostreams(sSearchStr){
	
	if(!sSearchStr){sSearchStr = $("input#vioUID").attr("value");}
	
	if(sSearchStr){
		var bHasResult = false;
		
		$("select#searchselect").html("");
		
		srchRespXML = fnSearchMedia(sSearchStr);
		
		if($(srchRespXML).find("MediaBase").length>0){
				fnSearchDisp('show');
				bHasResult = true;
			}

		if(bHasResult){	

			$(srchRespXML).find("MediaBase").each(
				function(){
					var sMediaType = $(this).attr("MediaType"); 
					var sMediaID = $(this).find("MediaId").text();
					var sMediaTitle = $(this).find("MediaTitle").text();
					var sOptionClass = "vio-aud";
					
					if(sMediaType.toLowerCase() == "video"){
						sOptionClass = "vio-vid";
						}
					$("select#searchselect").append('<option class="'+ sOptionClass +'" value="'+ sMediaID +'">'+ sMediaTitle +'</option>');
				}	
			);

		}else{
			alert("No matching media files found!");
		}
	}
}

function fnSearchSelected(){
	fnSearchDisp('hide');
	var sSearchUID = $("select#searchselect option:selected").attr("value");
	fnAddViostreamDetails(sSearchUID);
}
	
function fnSearchDisp(sToggle){
	if(sToggle=="show"){
	 $("div#vio-search-container").show();	
	}
	else{
	 $("div#vio-search-container").hide();	
	}
}

function fnSearchMedia(sSearchStr){

	sSearchStr = escape(sSearchStr);

	var XMLresponse;
	
	XMLresponse = $.ajax({
		type: "POST",
		url: "../access/viostream-service-proxy/viostream-service.asp",
		data: "id_string="+sSearchStr
				+"&id_key=searchWord"
				+"&method_name=MediaSearch",
		dataType: "xml",
		async: false
	   });
	
	 var XMLdoc = XMLresponse.responseXML.documentElement;
	
 
	 return XMLdoc;
}