
// global request and XML document objects
var req;
// global vars
var curTran; 		//Current Tranceiver: stores the value of the source or direction of the ajax request
var arrVideo;		//all video information within the chart (navigation)
var this_URL;		//url to the video playing.

function initDivs(){
	hidediv('saving-file');
}

function finishPlayList(){
//	if (clipType == 'wvpvc'){
//		playVCFlash(ver, zip, tid, zcode, rep, lvl)
//	}
}

function loadXMLDoc(url, transceiver) {
    showdiv('saving-file');
	curTran = transceiver;
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = processReqChange;
        req.open("GET", url, true);
        req.send(null);
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        isIE = true;
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = processReqChange;
            req.open("GET", url, true);
            req.send();
        }
    }
}


// handle onreadystatechange event of req object
function processReqChange() {
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
				channelResponse();
         } else {
            alert("There was a problem retrieving the XML data:\n" +
                req.statusText);
            hidediv('saving-file');
         }
    }
}

// handle onreadystatechange event of req object

/*  	channels or directs the response of the ajax function to
		the requester or the appropriate function		*/
function channelResponse() {
	switch (curTran) {
	case 'chart_new':
		buildArray('new');
		break;
	case 'chart_pop':
		buildArray('pop');
		break;
	case 'chart_top':
		buildArray('top');
		break;
	case 'chart_shr':
		buildArray('shr');
		break;
	case 'chart_sch':
		buildArray('sch');
		break;
	case 'rate':
		rateVideoResponse();
		break;	
	case 'subscribe':
		subscribeVideoResponse();
		break;
	case 'share':
		shareVideoResponse();
		break;
	case 'review':
		reviewVideoResponse();
		break;
	case 'reviews':
		reviewsResponse();
		break;
	case 'media':
		mediaVideoResponse();
		break;
	default :
		buildArray();
	}
	hidediv('saving-file');
}


/*		initialize function  */
function playerInit(BlnStart, isSpecial) {
   	var q = 'clipurl='+escape(clipUrl+'|'+oasUrl+'|'+clipType);
   	
   	if (isSpecial == 1)
   	{
   	    playNewFlash(contentDomain + clipUrl + '?' + q);
   	}
   	else
   	{
   	    playNewFlash3(contentDomain + 'Videos/RecordingYC/' + clipId + '/' + clipId + '.xml?' + q, -1, BlnStart);
   	}
}


/*  	Function creates the array for all videos displayed in the menu (chart).
		Stores all information about the videos in this array.  */
function buildArray(tab) {
	var x = req.responseXML.getElementsByTagName('video');    //xmlDoc.getElementsByTagName('video');

	arrVideo= new Array();
	for (i=0;i<x.length;i++)
	{
		arrVideo[i] = new Array();
		for (j=0;j<x[i].childNodes.length;j++)
		{
			var thjs = x[i].childNodes[j];
			if (thjs.nodeType != 1) continue;
			if (thjs.firstChild == null){
				arrVideo[i][thjs.nodeName]='';
			}else{
				arrVideo[i][thjs.nodeName]=thjs.firstChild.nodeValue;
			}
		}
	}
	createList(arrVideo, tab);
}

// ----

/*  	Function creates the video menu (chart)  */
function createList(_arr, _tab) {
	var th2 = '';
	switch (_tab) {
	case 'new':		//New
		th2 = 'date';
		break;
	case 'pop':		//Most Popular
		th2 = 'views';
		break;	
	case 'top':		//Top Rated
		th2 = 'rating';
		break;
	case 'shr':		//Most Shared
		th2 = 'shared';
		break;
	case 'sch':		//Search
		//additional logic to get variables of search
		th2 = 'date';
		break;
	default :
		th2 = 'date';
	}
	
	arrVideoList= new Array();
	var htmlx ='';
	htmlx += '<table border="0" cellspacing="0" cellpadding="0">';
		htmlx += '<tbody>';
			htmlx += '<tr class="video_list_cols">';
				htmlx += '<th id="video_list_title" class="video_list_title">';
					htmlx += 'title';
				htmlx += '</th>';
				htmlx += '<th id="video_list_date" class="video_list_date">';
					htmlx += th2;
				htmlx += '</th>';
			htmlx += '</tr>';
		
		for (i=0;i<_arr.length;i++)
		{
			arrVideoList[i] = _arr[i]['id'];
			htmlx += '<tr id="'+ _arr[i]['id'] +'" onClick=" playVideo(this, \'' + _arr[i]['id'] + '\', \''+ _arr[i]['url'] +'\');" onMouseOver="mhover(this, \'over\');" onMouseOut="mhover(this, \'out\');">';
				htmlx += '<td class="video_list_title">';
						htmlx += /*i+1 + '. ' + */ _arr[i]['title'];
				htmlx += '</td>';
				htmlx += '<td class="video_list_date">';
					htmlx += '(' + _arr[i][th2] + ')';
				htmlx += '</td>';
			htmlx += '</tr>';
		}
		htmlx += '</tbody>';
	htmlx += '</table>';
	document.getElementById('chart_list').innerHTML = htmlx;
	setVideoListTab(_tab);
}

/*  	Function makes mouse over (hover) possible for the menu (chart): 
		switches classes because switching styles is not as flexible.  */
function mhover(xelement, yswitch) {
	if (xelement.className!='video_list_playing') {
		if (yswitch == 'over') {
			xelement.className="video_list_hover";
		}
		if (yswitch == 'out') {
			xelement.className="";
		}
	}
}



/* 	gets the video index of elementx having value elementxVal
		and is useful for getting the index of the array based on the 
		unique id of the movie, to access other information about the video
		(could also be used to find the first index of non unique identifiers:
		 find the most popular of this_user in the array )  */
function getVideoIndex(elementx, elementxVal) {
	for (i=0;i<arrVideo.length;i++) {
		if (arrVideo[i][elementx] == elementxVal) {
			return i;
		}
	}
}

/*		i_player    */
var videoPlaying = Array('','')

function playVideo(xthis, xid, xurl) {
	if (xthis != videoPlaying[1]) {
		xthis.className = 'video_list_playing';
		if (videoPlaying[1].className) {
			videoPlaying[1].className = '';
		}
		videoPlaying[1] = xthis;
	
		var i = getVideoIndex('id', xid);  //array search for index of video based on id

		var nrand=Math.floor(Math.random()*100000000); 
		
		var xFrame = document.getElementById('video-frame');
		var vUrl = 'video.aspx';
		vUrl += '?clipid2=' + xid;
		vUrl += '&' + queryString;
		vUrl += '&' + nrand;
		xFrame.src = vUrl;
	}
}

/*		These functions are to be accessed as a result of a video change FROM the menu.
		These functions rely on the array of which the menu (chart) was built.  */
var arrTab = new Array();
	arrTab[0]='new';
	arrTab[1]='pop';
	arrTab[2]='top';
	arrTab[3]='shr';
	arrTab[4]='sch';
var prevTab = '';

function setVideoListTab(nextTab) {
	if (prevTab == '' || prevTab != nextTab ) { // check if we need to switch tabs

		for (i=0; i<arrTab.length; i++) {
			if (arrTab[i] == nextTab) {
				var tabSelected = arrTab[i];
				document.getElementById('chart_tab_'+arrTab[i]).className = 'chart_tab_'+arrTab[i]+'_on';
				prevTab = tabSelected;
			} else {
				document.getElementById('chart_tab_'+arrTab[i]).className = 'chart_tab_'+arrTab[i]+'_off';
			}
		}
	}
	//tabSelected = (tabSelected == null || tabSelected == 'undefined') ? ('new') : ( tabSelected );
}
		
function setVideoTitle(i) {
	var video_title = arrVideo[i]['title'].toUpperCase();	
	document.getElementById('video_title').innerHTML = video_title;
}

function setVideoUser(i) {
	var this_user = arrVideo[i]['user'];
	document.getElementById('this_user').innerHTML = this_user;
}

function setVideoDesc(i) {
	var desc = (arrVideo[i]['desc'] == '---') ? ('no description') : (arrVideo[i]['desc']);  // checks to make sure there is a description.
	document.getElementById('desc').innerHTML = desc;
}

function setVideoId(i) {
	var v_id = arrVideo[i]['id'];
	document.getElementById('share_id').value = v_id;
	document.getElementById('review_id').value = v_id;
}


/*		 Video Player Functions/Object		*/
function playNew(video_id, uid, blnStart, blnChangeZipCode) {
	if (blnChangeZipCode == undefined)
	{
		blnChangeZipCode = "0";
	}
	playNewFlash(clipUrl, -1, "true");
}

/*		 Video Windows Media Player Functions/Object		*/
//function playNewMedia(video_id, uid, blnStart) {
function playNewMedia(video_url, uid, blnStart) {
	document.getElementById('video_player').innerHTML='<object width="320" height="280"  align="center" hspace="1"  style="border: 0px solid #C4C5D3;" VIEWASTEXT '
      +'classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" '
      +'codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701" '
      +'standby="Loading Microsoft Windows Media Player components..." type="application/x-oleobject">'
      +'<param name="url" value="' + video_url + '">'
      +'<param name="uiMode" value="full">'
      +'<param name="TransparentAtStart" value="1">'
      +'<param name="autoStart" value="' + blnStart + '">'
      +'<embed type="application/x-mplayer2" '
      +'pluginspage="http://microsoft.com/windows/mediaplayer/en/download/" '
      +'showcontrols="true" uimode="full" width="320" height="280" hspace="10" '
      +'src="' + video_url + '" autostart="1">'
	  +'</object>';
		setVideoPlayerImage(imageUrl, imageClickUrl);
}

function playNewFlash3(video_url, uid, blnStart)
{
    var objS_SWF = contentDomain + "YC_Player_061208.swf";
    var objS_ID = "FLV_Player_Cue_07";
    var objS_Width = "320";
    var objS_Height = "280";
    var objS_Version = "8.0.22.0";
    var objS_BGColor = "#FFFFFF";
    var objS_ExpressInstall = true;
    var so = new FlashObject(objS_SWF, objS_ID, objS_Width, objS_Height, objS_Version, objS_BGColor, objS_ExpressInstall);

    so.addVariable("x", "x");
    so.addVariable("streamName", clipId);
    so.addVariable("playListXML", video_url); 
    so.addVariable("autoStart", "true");
    so.addVariable("contentDomain", contentDomain)
    so.addVariable("bgColor", "0xFFFFFF");
    so.addVariable("audioOnlyImage", "");
    so.addVariable("imageSequence", "");
    so.addVariable("x", "x");
    so.write("video_player");
    document.getElementById(objS_ID).focus();
}

function playNewFlash(video_url)
{
    var nrand=Math.floor(Math.random()*100000000); 
    var objS_SWF = contentDomain + "YC_Player_061208.swf";
    var objS_ID = "YC_Player_061208.swf";
    var objS_Width = "320";
    var objS_Height = "280";
    var objS_Version = "8.0.22.0";
    var objS_BGColor = "#FFFFFF";
    var objS_ExpressInstall = true;
    var so = new FlashObject(objS_SWF, objS_ID, objS_Width, objS_Height, objS_Version, objS_BGColor, objS_ExpressInstall);

    so.addVariable("x", "x");
    so.addVariable("playListXML", video_url+'&r='+nrand);
    so.addVariable("autoStart", "true");
    so.addVariable("bgColor", "0xDEDEDE");
    so.addVariable("x", "x");
    so.write("video_player");
    document.getElementById(objS_ID).focus();
}

/* 	Show video_player_image */
function setVideoPlayerImage(imageUrl, imageClickUrl) {
	var z = '<a href="' + imageClickUrl + '" target="_blank"><img src="' + imageUrl + '" border=0></a>';
	document.getElementById('video_player_image').innerHTML = z;
}


/*		Function for completing media video.  */
function mediaVideoResponse() {
	var vu = req.responseXML.getElementsByTagName('videoUrl'); 
	var iu = req.responseXML.getElementsByTagName('imageUrl'); 
	var icu = req.responseXML.getElementsByTagName('imageClickUrl'); 
	if (vu.length != 0 && iu.length != 0 && icu.length != 0) {
		for (i=0;i<vu.length;i++)	{
			var vuVal = vu[i].firstChild.nodeValue;
			imageUrl = iu[i].firstChild.nodeValue;
			imageClickUrl = icu[i].firstChild.nodeValue;
		}
		playNewMedia(vuVal, -1, 1);
	}
}

function subscribeThis(clipId){
	var subscribe_to = document.getElementById('subscribe_to').value;
	if (subscribe_to != '' &&  subscribe_to != 'Your Email' &&  
		subscribe_to != 'No Email address' &&  subscribe_to != 'Subscribed! Thank you.' &&
		subscribe_to != 'System busy. Please try again later.' &&
		subscribe_to.indexOf('@') != -1) {
		var subscribe_aspx = '/uCastServices/subscribe.aspx';
		
		var subscribe_url = subscribe_aspx;
		subscribe_url += '?clipid=' +clipId;
		subscribe_url += '&clipType=' + clipType;
		subscribe_url += '&email=' + encodeURI(subscribe_to);
		loadXMLDoc(subscribe_url, 'subscribe');
	} else {
		document.getElementById('subscribe_to').value = 'No Email address';
	}
}
/*		Function for initiating share video.  */
function shareThis() {
	var share_id = document.getElementById('share_id').value;
	if (share_id != '') {
		var share_aspx = '/uCastServices/shareClip.aspx';
		var share_to = document.getElementById('share_to').value;
		if (share_to.indexOf('@') != -1) {
			var share_from = document.getElementById('share_from').value;
			//var share_self = (document.getElementById('share_self').checked) ? ('yes') : ('no');
			
			var share_url = share_aspx;
			share_url += '?clipid=' +share_id;
			share_url += '&to=' + encodeURI(share_to);
			share_url += '&from=' + encodeURI(share_from);
			share_url += '&copyme=no';
			share_url += '&clipType=' + clipType;
			loadXMLDoc(share_url, 'share');
			//shareClip.aspx?clipid=123&to=ENCODE(to_email_address)&from=ENCODE(from_email_address)&copyme=yes/no      (returns SUCCESS/FAILURE)
		} else {
			document.getElementById('share_to').value = 'No Email address';
		}
	} else {
		document.getElementById('share_feedback').innerHTML = '<span style="color:#ff0000;">No Video Selected</span>';
	}
}

/*		Function for completing share video.  */
function shareVideoResponse() {
	var s = req.responseXML.getElementsByTagName('shared'); 
	if (s.length != 0) {
		document.getElementById('share_to').value = 'Sent! Thank you.';
		//var f = document.getElementById('share_feedback')
		//for (i=0;i<s.length;i++)	{
		//	f.innerHTML = 'Sent! Thank you.';
		//}
	
	} else {
		document.getElementById('share_to').value = 'System busy. Please try again later.';
		//f.innerHTML = '<span style="color:#ff0000;">Error, Please try again later.</span>';
	}
}
function subscribeVideoResponse() {
	var x = req.responseXML.getElementsByTagName('Clip'); 
	if (x.length != 0)
	{
		for (i=0;i<x.length;i++)	{
			var success = x[i].firstChild.nodeValue;
			if (success == 'DONE') {
				document.getElementById('subscribe_to').value = 'Subscribed! Thank you.';
			} else {
				document.getElementById('subscribe_to').value = 'System busy. Please try again later.';
			}
		}
	}
}

function reloadVideo()
{
	location.reload();
}

function submitVideo()
{
    var nowDate = new Date();
    source = loadSyncHttp(curDomain + '/Service/CreateNewYouCast.aspx', "" );
    if (source <=0)
    {
        window.alert("Unable to launch youCast recorder...please try again later.");	        
    }
    else
    {
        var t = Date.UTC(nowDate.getUTCFullYear(), nowDate.getUTCMonth(), nowDate.getUTCDate(), nowDate.getUTCHours(), nowDate.getUTCMinutes(), nowDate.getUTCSeconds());
        location.href = recorderUrl + "?clipid=" + source + "&t=" + t + "&zipcode=&userid=";
    }
}

function shareYc(to, from)
{
   source = loadSyncHttp(curDomain + '/Service/ShareYouCast.aspx', "to=" + to +"&from=" + from + "&source_id=" + clipId);
    if (source <=0)
    {
        window.alert("Error sharing this youCast...please try again later.");	        
    }
    else
    {
        window.alert("Thank you for sharing this youCast");
    }
}

function hidediv(id) {
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.display = 'none';
	}
	else {
		if (document.layers) { // Netscape 4
			document.id.display = 'none';
		}
		else { // IE 4
			document.all.id.style.display = 'none';
		}
	}
}

function showdiv(id) {
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.display = 'block';
	}
	else {
		if (document.layers) { // Netscape 4
			document.id.display = 'block';
		}
		else { // IE 4
			document.all.id.style.display = 'block';
		}
	}
}

/*		i_functions  */
/*		Validation Functions   */
	function hasValue(strValue)	{
		if(strValue.length == 0) {
			return false;
		}
	return true;
	}
	
	function isInteger(s)
	{   var i;
		for (i = 0; i < s.length; i++)
		{ 
			var c = s.charAt(i);
			if (((c < "0") || (c > "9"))) return false;
		}
		return true;
	}

	function replaceChars(_string, _nix, _add) {
		temp = "" + _string; // temporary holder
		while (temp.indexOf(_nix)>-1) {
			pos= temp.indexOf(_nix);
			temp = "" + (temp.substring(0, pos) + _add + 
			temp.substring((pos + _nix.length), temp.length));
		}
		return temp;
	}
	
	function trimString(sInString) {
	  sInString = sInString.replace( /^\s+/g, "" );// strip leading
	  return sInString.replace( /\s+$/g, "" );// strip trailing
	}

