/**
 *  IDA - common.js
 *  
 *  @version 1.0
 *	@author Leon Ng
 */


var fontMin=8;
var fontMax=18;
var resizeMinLimit = 1;
var resizeMaxLimit = 5;
var currentfontlevel = 3;

var currentGlanceNav = 1;
var currentSnapShot = 1;

var CookieName = "IDACookie";
var cookieFontSize = 0;
var expirydays = 30;

var ytplayer;
var duration;
var title1;
var title2;
var title3;
var videoDuration1;
var videoDuration2;
var videoDuration3;
var videoLink1;
var videoLink2;
var videoLink3;
var playlistUri;
var currentVideo = 1;


function init(){
	cookieFontSize = getCookie(CookieName);
	
	if(cookieFontSize == null){
		cookieFontSize = 3;
	}
	else{
		switch (cookieFontSize){
			case "5":
				fontSizeModify("inc");
				fontSizeModify("inc");
				break;
			case "4":
				fontSizeModify("inc");
				break;
			case "2":
				fontSizeModify("dec");
				break;
			case "1":
				fontSizeModify("dec");
				fontSizeModify("dec");
				break;
		}
	}
	
	if( $$("snapshots") != null ){
		$$("videoDesc1").innerHTML = "<a href=\"javascript: changeVideo('1')\" class=\"selected\">" + title1 + "</a> <span class='datetime'>" + videoDuration1 + "</span>";
		$$("videoDesc2").innerHTML = "<a href=\"javascript: changeVideo('2')\" >" + title2 + "</a> <span class='datetime'>" + videoDuration2 + "</span>";
		$$("videoDesc3").innerHTML = "<a href=\"javascript: changeVideo('3')\" >" + title3 + "</a> <span class='datetime'>" + videoDuration3 + "</span>";
	}
	
	// --- selection of the left navigation ---
	if(subSection != null){
		$$(subSection).addClass("selected");
	}	
}

function fontSizeModify(type){
	switch (type){
		case "dec":
			if(currentfontlevel != resizeMinLimit){
				for( var i = fontMin; i <= fontMax; ++i){
					if(i != fontMin){
						$$("main-content").elmsByClass("font"+i).addClass("font"+(i-1));
						$$("main-content").elmsByClass("font"+i).removeClass("font"+i);
					}
				}
				--currentfontlevel;
			}
			break;
		case "inc":
			if(currentfontlevel != resizeMaxLimit){
				for( var i = fontMax; i >= fontMin; --i){
					if(i != fontMax){
						$$("main-content").elmsByClass("font"+i).addClass("font"+(i+1));
						$$("main-content").elmsByClass("font"+i).removeClass("font"+i);
					}
				}
				++currentfontlevel;
			}
			break;
	}
	
	setCookie(CookieName, currentfontlevel, expirydays);
}


function showGlance(tabNo){
	$$("GlanceContent"+currentGlanceNav).addClass("hidden");
	$$("GlanceContent"+currentGlanceNav).removeClass("contentBox");
	$$("glanceNav"+currentGlanceNav).removeClass("opened");
	
	$$("GlanceContent"+tabNo).addClass("contentBox");
	$$("GlanceContent"+tabNo).removeClass("hidden");
	$$("glanceNav"+tabNo).addClass("opened");
	
	currentGlanceNav = tabNo;
}


function showhidePanel(container){
	if( $$(container+"Content").hasClass("hidePanel") ){
		$$(container+"Content").removeClass("hidePanel");
		$$(container+"Title").removeClass("boxclosed");
		$$(container+"Title").addClass("boxopen");
		$$(container+"TitleBox").removeClass("panelheader");
		$$(container+"TitleBox").addClass("panelheaderOpen");
	}else{
		$$(container+"Content").addClass("hidePanel");
		$$(container+"Title").addClass("boxclosed");
		$$(container+"Title").removeClass("boxopen");
		$$(container+"TitleBox").addClass("panelheader");
		$$(container+"TitleBox").removeClass("panelheaderOpen");
	}
}


function showhidesSnapShots(panel){
	$$("snapshotPanel"+currentSnapShot).addClass("hidden");
	$$("snapshotPanel"+currentSnapShot).removeClass("content");
	$$("snapshotNav"+currentSnapShot).removeClass("selected");
	
	$$("snapshotPanel"+panel).removeClass("hidden");
	$$("snapshotPanel"+panel).addClass("content");
	$$("snapshotNav"+panel).addClass("selected");
	
	if(panel == 1)
		$$("snapshotsContent").removeClass("hidden");
	else
		$$("snapshotsContent").addClass("hidden");
	
	currentSnapShot = panel;
}

// ----- Cookies Check and functions -----------
function getCookie(NameOfCookie){
	if (document.cookie.length > 0){

	begin = document.cookie.indexOf(NameOfCookie+"=");
	
	if (begin != -1) {
		begin += NameOfCookie.length+1;
		end = document.cookie.indexOf(";", begin);
		
		if (end == -1) end = document.cookie.length;
			return unescape(document.cookie.substring(begin, end)); 
		}
	}
		
	return null;
}

function setCookie(NameOfCookie, value, expiredays){
	var ExpireDate = new Date ();
	ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000));

	document.cookie = NameOfCookie + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString() + "; path=/");
}

function deleteCookie (NameOfCookie){
	if (getCookie(NameOfCookie)) 
		document.cookie = NameOfCookie + "=" +"; expires=Thu, 01-Jan-90 00:00:01 GMT; path=/";
}


// ---- For the SnapsShot section ( video and flickr images ) ----
var playlist = null;
var playlistFeedLink = null;
var videoURI;

function onYouTubePlayerReady(playerId) {
	ytplayer = document.getElementById("videoPlayer");
	ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

function onytplayerStateChange(newState) {
   duration = ytplayer.getDuration();
   $$("videoTime").innerHTML = duration;
}


function VideoLoaded(data){
	var feed = data.feed;
	var entries = feed.entry || [];
	
	for( var i = 1; i < 4; ++i ){
		if(typeof(entries[i-1]) !== 'undefined'){
			window['title' + i] 			= entries[i-1].title.$t;
			window['videoLink' + i]			= entries[i-1].media$group.media$content[0].url;
			
			// Change seconds into mins & secs
			var totalSeconds = entries[i-1].media$group.media$content[0].duration;
			
			window['videoDuration' + i] 	= Math.floor(totalSeconds / 60) + " mins " + (totalSeconds % 60) + " secs";
		}
	}
	
	// default load play the first video
	loadVideo(videoLink1, false);
}

function changeVideo(videoNo){
	$$("videoDesc"+videoNo).elmsByAttribute("href").addClass("selected");
	$$("videoDesc"+currentVideo).elmsByAttribute("href").removeClass("selected");
	loadVideo(window['videoLink'+videoNo], false);
	currentVideo = videoNo;
}

function ProcessFeedRequest(data){

}

function loadVideo(playerUrl, autoplay) {
	var params = { allowScriptAccess: "always", allowfullscreen: "true" };
	var atts = { id: "videoPlayer" };
	swfobject.embedSWF(playerUrl + '&rel=1&showsearch=1&border=0&playerapiid=videoPlayer&fs=1&autoplay=' + (autoplay?1:0), "videoPlayer", "280", "206", "8", null, null, params, atts);
}

function PrintThisPage()  { 
	var w=650;
      	var h=600;
      	var l=2;
      	var t=2;
      	l=(screen.availWidth-w)/2;
      	t=(screen.availHeight-h)/2;

	var sOption="toolbar=no,location=no,directories=no,menubar=no,"; 
	sOption+="scrollbars=yes,width="+ w  +",height="+ h +",left="+ l +",top="+ t +""; 			   

	var winprint=window.open("/Common/printthispage.aspx","Print",sOption); 			 
	winprint.focus(); 
}

function GetPrintContent() {     
	var PrintDiv =  document.getElementById('printcontent');
	var PrintHeader =  document.getElementById('printheader');
	var ContentDiv =  window.opener.document.getElementById('printerfriendly');
	var HeaderDiv =   window.opener.document.getElementById('mainHeader');
        var Parent_Title =  window.opener.document.title;
        document.title=Parent_Title;
	PrintDiv.innerHTML = ContentDiv.innerHTML;      
	PrintHeader.innerHTML = HeaderDiv.innerHTML;      
	
	var ai=0;
	for(ai=0;ai<document.getElementsByTagName('a').length;ai++) {
		if(document.getElementsByTagName('a')[ai].id=="printpageurl") {
			document.getElementsByTagName('a')[ai].href=window.opener.location.href;
			document.getElementsByTagName('a')[ai].target='_blank'; 
			document.getElementsByTagName('a')[ai].innerHTML=window.opener.location.href;  
		}
               	else {
			document.getElementsByTagName('a')[ai].href='#';
			document.getElementsByTagName('a')[ai].target='_self';            
		}
	}
}

function textareaCounter(messageId, counterId, maxChars)
{
	var myTextArea=document.getElementById(messageId);
	var myCounter=document.getElementById(counterId);
	if (myTextArea.value.length > maxChars) myTextArea.value = myTextArea.value.substring(0, maxChars);
	else myCounter.value = maxChars - myTextArea.value.length;
}

function numbersonly(myfield, e, dec)
{
	var key;
	var keychar;
	
	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	keychar = String.fromCharCode(key);
	
	// control keys
	if ((key==null) || (key==0) || (key==8) ||
		(key==9) || (key==13) || (key==27) )
	   return true;
	
	// numbers
	else if ((("-0123456789").indexOf(keychar) > -1))
	   return true;
	
	// decimal point jump
	else if (dec && (keychar == "."))
	   {
	   myfield.form.elements[dec].focus();
	   return false;
	   }
	else
	   return false;
}

function letternumber(e)
{
	var key;
	var keychar;
		
	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	
	keychar = String.fromCharCode(key);
	keychar = keychar.toLowerCase();
		
	// control keys
	if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
		return true;
		
	// alphas and numbers
	else if ((("\"!@#$^&*()_-+=|\{}[]:;'\,.?/abcdefghijklmnopqrstuvwxyz0123456789@ ").indexOf(keychar) > -1))
	   return true;
	else
	   return false;
}

DOMAssistant.DOMReady(init);