/*
PURPOSE: Holds ALL of the client side script functionality required for the end ms site
	     As a single root object
CREATED: April 30, 2008
CREATOR: Keith Chadwick
HISTORY:



OBJECT DOCUMENTATION
Pleaes ensure that any additional methods are documented here at the top of the file
to allow for easy documenation later

GLOBAL VARS DECLARED AT PAGE LEVEL
__PAGEID    =   Umbraco Page id
__PAGENAME  =   Umbraco Page Name


// EndMS OBJECT DOC
endMS                           -> base class
    .init                       -> initialization function passed the page id
    .search                     -> base search class
        .init                   -> initialize search function
    .blog                       -> base blog class
        .goArchive              -> redirect and pass to blog search page
*/


var endMS={
    init:function(){
    	TextResize();
		FeatureBoxResize();
    },


    jumpToPage:{
        address:'',
        container:'',
        count:5,
        itv:Object(),

        init:function(address,container,time){
            endMS.jumpToPage.count=time
        //return
            endMS.jumpToPage.address=address
            endMS.jumpToPage.container=container
            endMS.jumpToPage.itv=window.setInterval(endMS.jumpToPage.next,1000)
        },
        next:function(){
            if(document.getElementById(endMS.jumpToPage.container)){
                document.getElementById(endMS.jumpToPage.container).innerHTML=endMS.jumpToPage.count
            }
            endMS.jumpToPage.count=endMS.jumpToPage.count-1
            if(endMS.jumpToPage.count<=0){
                window.clearInterval(endMS.jumpToPage.itv)
                window.location.href=endMS.jumpToPage.address
            }
        }

    },

    util:{
        clearTB:function(obj){
            if(obj.value.length==0){
                obj.style.cssText=''
            }
        }

    },

    search:{
        init:function(){},
        onfocus:function(obj){obj.value=''},
        onclick:function(path){
            window.location.href=path+'?search='+document.getElementById('searchValue').value
        }

    },

    newsletter:{
        register:function(){}
    },

    blog:{
        // redirect to page on archive selection in blog
        goArchive:function(caller, url){
            window.location.href=url+caller.value
        },
        goSearch:function(value,url){
            window.location.href=url+'?type=search&amp;filter='+document.getElementById(value).value
        }
    },

    openSimulator:function(lang){
        window.open('/control/fundingsimulator.aspx?lang='+lang,'_blank','resizable=yes,width=940,height=655, scrollbars=no ,menubar=no, scrollbars=no, status=yes, titlebar=no, toolbar=no')
    },

    goFeedBurner:function(strUrl,strTitle,strLang,strEmail){

        var feedid=2450720
        strTitle='stopSP Blogue'
        if(strLang=='ENGLISH'){
            feedid=2447895
            strTitle='endMS Blog'
        }

        var frm=document.createElement('FORM');
        frm.action='http://www.feedburner.com/fb/a/emailverify';
        frm.method='post';
        frm.target='_new';
        frm.onSubmit=function(){
            window.open(strUrl+feedid, 'popupwindow', 'scrollbars=yes,width=550,height=520');
            return false
        };
        var url=document.createElement('input');
        url.name='url';
        url.value='http://feeds.feedburner.com/~e?ffid='+feedid;
        frm.appendChild(url)

        var title=document.createElement('input');
        title.name='title';
        title.value=strTitle
        frm.appendChild(title)

        var lang=document.createElement('input');
        lang.name='loc'
        lang.value='en_US';
        frm.appendChild(lang)

        var email=document.createElement('input')
        email.name='email';
        email.value=strEmail;
        frm.appendChild(email)

        document.body.appendChild(frm)
        frm.submit();

    },

    quicklinks:{
        show:function(e){
            document.getElementById('quicklinksmenu').style.display='block'
            document.getElementById('quicklinksmenu').focus()
            document.getElementById('quicklinksmenu').onmouseout=endMS.quicklinks.hide

        },
        hide:function(e){
            var ev=(!e)?window.event.toElement:e.relatedTarget;
            if(ev.parentNode.id=='quicklinksmenu' ){return}
            document.getElementById('quicklinksmenu').style.display='none'
        }

    },

    video:{
        goJump:function(playerId, eventName, eventParams){
            if(eventName=='stateChanged' && eventParams.state=='buffering'){
                document.getElementById(playerId).pauseMovie();
                window.location.href=document.getElementById('pageUrl'+playerId).value;
            }
        },

        manage:function(playerId, eventName, eventParams){
            // for future use if required
        },

        onFileSelected:function(file){
            document.getElementById('file_name').value = file.name;
        },

        onProgress:function(event){
            var p=(parseInt(event.ratio * 10000) / 100);
            document.getElementById('status').innerHTML = p + '%';
        },

        onUploadComplete:function(){
            document.getElementById('stage2').style.display='none'
            document.getElementById('scrapbook_8_divFeedBackFinish').style.display='block'
            document.getElementById('scrapbook_8_pnlBtnPost').style.display='block'
        },

        onUploadError:function(text){
            document.getElementById('status').innerHTML = 'Upload Error: ' + text + ' please try again';
            document.getElementById('stage1').style.display='block'
            document.getElementById('stage2').style.display='none'
        },

        onEmbedCodeReady:function(embedCode){
            document.getElementById('scrapbook_8_videoEmbedCode').value = embedCode;
        },

        startUpload:function(){
            try{
              ooyalaUploader.setTitle(document.getElementById('file_name').value);
              ooyalaUploader.setDescription(document.getElementById('scrapbook_8_posterTitle').value);
              var errorText = ooyalaUploader.validate();
              if (errorText){
                alert(errorText);
                return false;
              }
              document.getElementById('stage1').style.display='none'
              document.getElementById('stage2').style.display='block'
              ooyalaUploader.upload();
            }catch(e){
              alert(e);
            }
            return false;
        },
        doBinding:function(videoKey){
            try{
                ooyalaUploader.setParameters(videoKey);
                ooyalaUploader.addEventListener('fileSelected', 'endMS.video.onFileSelected');
                ooyalaUploader.addEventListener('progress', 'endMS.video.onProgress');
                ooyalaUploader.addEventListener('complete', 'endMS.video.onUploadComplete');
                ooyalaUploader.addEventListener('error', 'endMS.video.onUploadError');
                ooyalaUploader.addEventListener('embedCodeReady', 'endMS.video.onEmbedCodeReady');
            }catch(e){
              alert(e);
            }
            document.getElementById('scrapbook_8_pnlBtnPost').style.display='none'

        }
    },

    toString:{}
}



/*==============================================================================
 thin data functions
/*==============================================================================*/

	// This main function is responsible for parsing the query string
	// and populating matching fields in this online form.

	//---------------------------------------
	function preLoadData(strPassedFormName)
	//---------------------------------------
	{
	  var strTemp;
	  var strFormType;
	  var qsName;
	  var qsValue;
	  var arrPassedString;
	  var intI, intJ;
	  var urlPassedString = location.search.substring(1);
	  var re = /[+]/gi;
	  var blnFoundValidItem = 0;

	  // Look for at least one item in the query string that corresponds to
	  // PIID, MLID, or MPID.  If we find at least one item with that designation,
	  // then continue the preloading of the form.  Otherwise, do not go into the
	  // preload script

	  arrPassedString = urlPassedString.split("&")
	  for (intI = 0; intI < arrPassedString.length; intI++) {
		qsName = '';
		qsName = arrPassedString[intI].substring(0, 4);
		qsName = qsName.toUpperCase();
		if (qsName == 'PIID' || qsName == 'MLID' || qsName == 'MPID') {
		  blnFoundValidItem = 1;
		}
	  }


	  // parse our string of data into it's appropriate name and value pairs

	  if (urlPassedString.length != 0 && blnFoundValidItem == 1)
	  {
		for (intJ = 0; intJ < window.document.forms[strPassedFormName].length; intJ++) {
		  varFormElement = window.document.forms[strPassedFormName][intJ];
		  strFormType    = varFormElement.type;
		  strFormType = strFormType.toUpperCase();
		  if (strFormType == "TEXT"  || strFormType == "HIDDEN") {
			strTemp = varFormElement.name;
			strTemp = strTemp.toUpperCase();
			if (strTemp != "WEBFORMID" && strTemp != "PROCESSPAGE" && strTemp != "W" && strTemp != "CID" && strTemp != "I") {
			  varFormElement.value = "";
			}
		  } else if (strFormType == "CHECKBOX" || strFormType == "RADIO") {
			varFormElement.checked = false;
		  } else if (strFormType == "SELECT-ONE") {
			varFormElement.selectedIndex = -1;
		  } else if (strFormType == "TEXTAREA") {
			varFormElement.value = "";
		  }
		}
		arrPassedString = urlPassedString.split("&")
		for (intI = 0; intI < arrPassedString.length; intI++) {
		  qsValue = '';
		  qsName = '';
		  qsName = arrPassedString[intI].substring(0, arrPassedString[intI].indexOf("=",1));
		  qsValue = arrPassedString[intI].substring(arrPassedString[intI].indexOf("=",1)+1)
		  if (qsValue.substring(0, 1) == "+") {
			qsValue = qsValue.substring(1, qsValue.length)
		  }
		  qsValue = unescape(qsValue.replace(re, " "));
		  qsName = unescape(qsName.replace(re, " "));
		  if (window.document.forms[strPassedFormName][qsName]) {

			// Determine wether the profile item has been listed on the form multiple
			// times (in the case of a checkbox or radio button or select box with
			// multiple options) or if it's just listed once (in the case of everything else)

			if (window.document.forms[strPassedFormName][qsName].length) {
			  strFormType = window.document.forms[strPassedFormName][qsName].type;
			  if (strFormType) {
				strFormType = strFormType.toUpperCase();
			  }
			  if (strFormType == "TEXT"  || strFormType == "HIDDEN") {
				window.document.forms[strPassedFormName][qsName].value = qsValue;
			  } else if (strFormType == "RADIO" || strFormType == "CHECKBOX") {
				if (window.document.forms[strPassedFormName][qsName].value == qsValue) {
				  window.document.forms[strPassedFormName][qsName].checked = true;
				}
			  } else if (strFormType == "SELECT-ONE") {
				for (intJ = 0; intJ < window.document.forms[strPassedFormName][qsName].length; intJ++) {
				  strTemp = window.document.forms[strPassedFormName][qsName].options[intJ].value;
				  if (strTemp == qsValue) {
					window.document.forms[strPassedFormName][qsName].selectedIndex = intJ;
				  }
				}
			  } else {

				// We have a checkbox or radio button with multiple values.
				// In each case we know that there will be a value attribute

				for (intJ = 0; intJ < window.document.forms[strPassedFormName][qsName].length; intJ++) {
				  if (window.document.forms[strPassedFormName][qsName][intJ].value == qsValue) {
					window.document.forms[strPassedFormName][qsName][intJ].checked = true;
				  }
				}
			  }
			} else {

			  // We know that we either have a select box or we have something else.
			  // Test for the selectedIndex property to determine.

			  strFormType = window.document.forms[strPassedFormName][qsName].type;
			  strFormType = strFormType.toUpperCase();
			  if (strFormType == "SELECT-ONE") {
				for (intJ = 0; intJ < window.document.forms[strPassedFormName][qsName].length; intJ++) {
				  strTemp = window.document.forms[strPassedFormName][qsName].options[intJ].value;
				  if (strTemp == qsValue) {
					window.document.forms[strPassedFormName][qsName].selectedIndex = intJ;
				  }
				}
			  } else {
				strFormType = window.document.forms[strPassedFormName][qsName].type;
				strFormType = strFormType.toUpperCase();
				if (strFormType == 'RADIO' || strFormType == 'CHECKBOX') {
				  if (window.document.forms[strPassedFormName][qsName].value == qsValue) {
					window.document.forms[strPassedFormName][qsName].checked = true;
				  }
				} else {
				  window.document.forms[strPassedFormName][qsName].value = qsValue;
				}
			  }
			}
		  }
	 else {  qsName = qsName + '_0';       if (window.document.forms[strPassedFormName][qsName]) {

			// Determine wether the profile item has been listed on the form multiple
			// times (in the case of a checkbox or radio button or select box with
			// multiple options) or if it's just listed once (in the case of everything else)

			if (window.document.forms[strPassedFormName][qsName].length) {
			  strFormType = window.document.forms[strPassedFormName][qsName].type;
			  if (strFormType) {
				strFormType = strFormType.toUpperCase();
			  }
			  if (strFormType == "TEXT"  || strFormType == "HIDDEN") {
				window.document.forms[strPassedFormName][qsName].value = qsValue;
			  } else if (strFormType == "RADIO" || strFormType == "CHECKBOX") {
				if (window.document.forms[strPassedFormName][qsName].value == qsValue) {
				  window.document.forms[strPassedFormName][qsName].checked = true;
				}
			  } else if (strFormType == "SELECT-ONE") {
				for (intJ = 0; intJ < window.document.forms[strPassedFormName][qsName].length; intJ++) {
				  strTemp = window.document.forms[strPassedFormName][qsName].options[intJ].value;
				  if (strTemp == qsValue) {
					window.document.forms[strPassedFormName][qsName].selectedIndex = intJ;
				  }
				}
			  } else {

				// We have a checkbox or radio button with multiple values.
				// In each case we know that there will be a value attribute

				for (intJ = 0; intJ < window.document.forms[strPassedFormName][qsName].length; intJ++) {
				  if (window.document.forms[strPassedFormName][qsName][intJ].value == qsValue) {
					window.document.forms[strPassedFormName][qsName][intJ].checked = true;
				  }
				}
			  }
			} else {

			  // We know that we either have a select box or we have something else.
			  // Test for the selectedIndex property to determine.

			  strFormType = window.document.forms[strPassedFormName][qsName].type;
			  strFormType = strFormType.toUpperCase();
			  if (strFormType == "SELECT-ONE") {
				for (intJ = 0; intJ < window.document.forms[strPassedFormName][qsName].length; intJ++) {
				  strTemp = window.document.forms[strPassedFormName][qsName].options[intJ].value;
				  if (strTemp == qsValue) {
					window.document.forms[strPassedFormName][qsName].selectedIndex = intJ;
				  }
				}
			  } else {
				strFormType = window.document.forms[strPassedFormName][qsName].type;
				strFormType = strFormType.toUpperCase();
				if (strFormType == 'RADIO' || strFormType == 'CHECKBOX') {
				  if (window.document.forms[strPassedFormName][qsName].value == qsValue) {
					window.document.forms[strPassedFormName][qsName].checked = true;
				  }
				} else {
				  window.document.forms[strPassedFormName][qsName].value = qsValue;
				}
			  }
			}
		  }
		}     }
	  }
	}


	//------------------------------------------
	function testPreLoadToken(strPassedFormName)
	//------------------------------------------
	{
	  var urlPassedString = location.search.substring(1);
	  var re = /[+]/gi;
	  var strWebFormID = "";
	  var strINST = "";
	  var strTemp = "";
	  var intFoundToken = 0;
	  var varElement;
	  var strCompanyID = "";


	  // parse our string of data into it's appropriate name and value pairs

	  if (urlPassedString.length != 0)
	  {
		arrPassedString = urlPassedString.split("&")
		for (intI = 0; intI < arrPassedString.length; intI++) {
		  qsValue = '';
		  qsName = '';
		  qsName = arrPassedString[intI].substring(0, arrPassedString[intI].indexOf("=",1));
		  qsValue = arrPassedString[intI].substring(arrPassedString[intI].indexOf("=",1)+1)
		  if (qsValue.substring(0, 1) == "+") {
			qsValue = qsValue.substring(1, qsValue.length)
		  }
		  qsValue = unescape(qsValue.replace(re, " "));
		  qsName = unescape(qsName.replace(re, " "));
		  qsName = qsName.toUpperCase();
		  if (qsValue == "") qsValue="1";
		  if (qsName == "TOKEN" && qsValue != "") {
			intFoundToken = 1;

			// Find the original Online Form ID

			if (window.document.forms[strPassedFormName]["W"]) {
			  strWebFormID = window.document.forms[strPassedFormName]["W"].value;
			}
			if (window.document.forms[strPassedFormName]["I"]) {
			  strINST = window.document.forms[strPassedFormName]["I"].value;
			}
			if (strWebFormID != "") {
			  strTemp = "http://ems01.com/a/y.x?S=" + qsValue + "&W=" + strWebFormID + "&I=" + strINST + "&U="  + escape(window.location);
			  window.location = strTemp;
			}
		  }
		}
	  }
	}

	//---------------------------------------------------------------------
	 function TurnOtherOff(intMimeTypeId,lngMailinglistId,objthis,thisform)
	//---------------------------------------------------------------------
	{
	   var strTextTypeBox = 'MLID_' + lngMailinglistId + '_2';
	   var strHTMLTypebox = 'MLID_' + lngMailinglistId + '_4';
	   var frmWebform = window.document.forms[thisform];

	   if(intMimeTypeId==2)
	   {
		 for(i=0;i<frmWebform.length;i++)
		 {
		   if(frmWebform.elements[i].name.indexOf(strHTMLTypebox)!=-1)
		   {
			 if (objthis.checked == true)
			 {
			   frmWebform.elements[i].checked = false;
			 }
		   }
		}
	  }

	   if(intMimeTypeId==4)
	   {
		 for(i=0;i<frmWebform.length;i++)
		 {        if(frmWebform.elements[i].name.indexOf(strTextTypeBox)!=-1)
		   {          if (objthis.checked == true)
			 {
				frmWebform.elements[i].checked = false;
			 }
		   }
		 }
	   }
	 } //end function


	//---------------------------------------------------------------------
	function TextResize()
	//---------------------------------------------------------------------
	{
		if(!document.getElementById("resize"))
		{
			return false;
		}

		var resizeLinks = document.getElementById("resize").getElementsByTagName("dd")[0].getElementsByTagName("a");

		for(var x = 0; x < resizeLinks.length; x++)
		{
			resizeLinks[x].onclick = function() {
				setActiveStyleSheet(this.title.toLowerCase());
				FeatureBoxReset();
				FeatureBoxResize();
				return false;
			};
		}
	} // end function


	//---------------------------------------------------------------------
	function FeatureBoxReset()
	//---------------------------------------------------------------------
	{
		if(document.getElementById('ftr-community') && document.getElementById('ftr-blog') && document.getElementById('ftr-campaign'))
		{
			var ftrHeight = new Array();

			ftrHeight.push(document.getElementById('ftr-community'));
			ftrHeight.push(document.getElementById('ftr-blog'));
			ftrHeight.push(document.getElementById('ftr-campaign'));

			for(var x = 0; x < ftrHeight.length; x++)
			{
				ftrHeight[x].getElementsByTagName('div')[0].style.height = 'auto';
			}
		}
		else if(document.getElementById('ftr-video') && document.getElementById('ftr-photo') && document.getElementById('ftr-stories'))
		{
			var ftrHeight = new Array();

			ftrHeight.push(document.getElementById('ftr-video'));
			ftrHeight.push(document.getElementById('ftr-photo'));
			ftrHeight.push(document.getElementById('ftr-stories'));

			for(var x = 0; x < ftrHeight.length; x++)
			{
				ftrHeight[x].getElementsByTagName('div')[0].style.height = 'auto';
			}
		}
		else
		{
			return false;
		}
	} // end function


	//---------------------------------------------------------------------
	function FeatureBoxResize()
	//---------------------------------------------------------------------
	{
		if(document.getElementById('ftr-community') && document.getElementById('ftr-blog') && document.getElementById('ftr-campaign'))
		{
			var ftrHeight = new Array();
			var maxHeight = 0;

			ftrHeight.push(document.getElementById('ftr-community'));
			ftrHeight.push(document.getElementById('ftr-blog'));
			ftrHeight.push(document.getElementById('ftr-campaign'));

			for(var x = 0; x < ftrHeight.length; x++)
			{
				maxHeight = (ftrHeight[x].offsetHeight > maxHeight) ? ftrHeight[x].offsetHeight : maxHeight;
			}

			for(var x = 0; x < ftrHeight.length; x++)
			{
				ftrHeight[x].getElementsByTagName('div')[0].style.height = parseInt(maxHeight - 66) + 'px';
			}
		}
		else if(document.getElementById('ftr-video') && document.getElementById('ftr-photo') && document.getElementById('ftr-stories'))
		{
			var ftrHeight = new Array();
			var maxHeight = 0;

			ftrHeight.push(document.getElementById('ftr-video'));
			ftrHeight.push(document.getElementById('ftr-photo'));
			ftrHeight.push(document.getElementById('ftr-stories'));

			for(var x = 0; x < ftrHeight.length; x++)
			{
				maxHeight = (ftrHeight[x].offsetHeight > maxHeight) ? ftrHeight[x].offsetHeight : maxHeight;
			}

			for(var x = 0; x < ftrHeight.length; x++)
			{
				ftrHeight[x].getElementsByTagName('div')[0].style.height = parseInt(maxHeight - 66) + 'px';
			}
			ftrHeight[0].getElementsByTagName('div')[0].style.height = parseInt(maxHeight - 59) + 'px';
		}
		else
		{
			return false;
		}
	} // end function