////*************************************************************************************************************
//Program Name : Accessories.js
//Description  : Additional JS functions
//Company Name : Element K Middle East
//Developer    : Toji Abraham Mathew
//Date Created : 30 August 2006
//Revised On   : 26-Jul-2009, 27,28,29
//*************************************************************************************************************


//used to trim spaces from both sides of a string value.
//strVal parameter is the string which we need to trim.
function trim(strVal) 
{
    //does left trim
    while (strVal.substring(0,1) == ' ')
    {
        strVal = strVal.substring(1, strVal.length);
    }
    //does right trim
    while (strVal.substring(strVal.length-1, strVal.length) == ' ')
    {
        strVal = strVal.substring(0,strVal.length-1);
    }
    return strVal;
}



function getCookie(c_name,doc)
{
    var dc =null
    if(doc!=null){dc=doc;}
    else{ dc = document;}

if (dc.cookie.length>0)
  {
  c_start=dc.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=dc.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=dc.cookie.length;
    return unescape(dc.cookie.substring(c_start,c_end));
    }
  }
return "";
}



//This function gives us all the client informations about a control.
//thisId is the id of the control of which we shouold get the information.
//for better use display the informations to a alert box or textarea control.
//eg: document.getElementById('TextArea1').value = getControlInfo(<Id_Of_Your_Control>)
function getControlInfo(thisId) 
{
    var strVal = '';
    for(cnt=0;cnt<=thisId.attributes.length-1;cnt++)
    {
       strVal += cnt + '. ' + thisId.attributes.item(cnt).name + ' = '+ thisId.attributes.item(cnt).value + '\n'
    }
    return (strVal)
}



function DrpVisTooltip ( idObject ) 
{ 		
//alert(idObject)	
	var obj = document.getElementById( idObject ); 
	//alert(obj)
	//document.getElementById("tooltip").innerHTML = obj.options[obj.selectedIndex].text;
	//document.getElementById("tooltip").innerHTML = obj.options[obj.selectedIndex].value;

	try{
	window.status=obj.options[obj.selectedIndex].text
	}catch(err){}

	
	/*if(obj.options[obj.selectedIndex].value !="") 
	{
		//document.getElementById("tooltip").style.zIndex = 9999999; 
 		document.getElementById("tooltip").style.zIndex = 0; 
  		document.getElementById("tooltip").style.display = "inline"; 
  		document.getElementById("tooltip").style.position = "absolute"; 
 		document.getElementById("tooltip").style.border =  "ActiveBorder  1px	solid"  ; 
		document.getElementById("tooltip").style.padding =   "3px";  
		document.getElementById("tooltip").style.fontSize =  "10px"; 
		document.getElementById("tooltip").style.fontFamily = "Verdana"; 
		document.getElementById("tooltip").style.backgroundColor = "LemonChiffon"; 
		document.getElementById("tooltip").style.top = document.getElementById(idObject).style.top + 250
		document.getElementById(idObject).offsetTop + document.getElementById(idObject).offsetHeight + "px";   
		document.getElementById("tooltip").style.left =	5 + event.x;
	}*/      
} 

function DrpHidTooltip ( )
{ 
  //document.getElementById("tooltip").style.display = "none"; 
  window.status = '';
}

//this enables to check IE browser versions. eg: if (IEVersion() < 7
  function IEVersion() 
  {
    var version = 999; // we assume a sane browser
    if (navigator.appVersion.indexOf("MSIE") != -1)
      // bah, IE again, lets downgrade version number
      version = parseFloat(navigator.appVersion.split("MSIE")[1]);
    return version;
  }
  
  
  
function getBrowser() {
    var browser = "";

    var name = navigator.userAgent.toLowerCase();
    
    if ( name.indexOf( "opera" ) != -1 ) {
        browser = "opera";
    } 
    else if ( name.indexOf( "msie" ) != -1 ) {
        browser = "msie";
    } 
    else if ( name.indexOf( "safari" ) != -1 ) {
        browser = "safari";
    } 
    else if ( name.indexOf( "mozilla" ) != -1 ) 
    {
        if ( name.indexOf( "firefox" ) != -1 ) {
            browser = "firefox";
        } else {
            browser = "mozilla";
        }
    }
    return browser;
} 

//popups should be allowed in this site
function checkpb(){
    var pb=getCookie('pb');
    //alert(location.href + '  :  ' +pb.toString());
    if(pb==1){
        var win = window.open('','','width=1,height=1,left=99999,top=99999,scrollbars=no');
        if(win){
            //alert('enabled');
            win.blur();
            if(getURLInQueryString('child')){
               //childpage = getURLInQueryString('child').replace(/"/g,'');
               childpage = getURLInQueryString('child');
               setck('pb',0);
               //alert('pb set here to 0 ' + document.location);
               location.href = decodeURI(childpage); 
            }
            win.close();
        } 
        else{
            //alert('disabled');
            setck('pb',"");
            //alert('pb set here to "" ' + document.location);
            childpage = getURLInQueryString('child');
            //alert('SessionOut.aspx?pb=1&child=' + childpage);
            location.href='SessionOut.aspx?pb=1&child=' + childpage;
        }
     }   
}   


//redirects to pbcheck.htm to check for popup allowed or not.
function ppBlockCheck()
{
    var pb=getCookie('pb');
    if(pb==""){
        //alert('block check');
        setck('pb',1);
        //alert('pb set here  to 1 ' + document.location);
        //location.href='pbcheck.htm?child="' + escape(location.href) + '"';
        var sPath = window.location.pathname;
        //alert(sPath);
        location.href='pbcheck.aspx?child=' + sPath.substring(sPath.lastIndexOf('/') + 1);
    }
}

  
//
//return the 1st queryString only.
//this is specifically made for playing with frame.
//
function getURLInQueryString(paramName){
  var queryStrs = "";
    if(window.location.search.indexOf(paramName)>=1) {
        var gotValue = false
        queryStrs = window.location.search.substring("?".length + paramName.length + "=".length);
    }
    return queryStrs;
}


//setting the admin.aspx or candidate.aspx page url into this cookie(frame page) to understand
//which page was requested by the user initially.
function setfp(){
    document.cookie="fp=" + top.location.href.toLowerCase();
    //ppBlockCheck();
}

function clearfp(){
    document.cookie="fp=";
}


function setck(ckname, val, doc){
    var dc =null
    if(doc!=null){dc=doc;}
    else{ dc = document;}
    dc.cookie=ckname + "=" + val;
}

  
  //this gets the height of the client area of a browser window.
  //this supports all browser versions
  function getDocHeight() {
    var D = document;
    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
 }
 
//Called in login pages to make sure that no one is gone to the login pages directly.
function isInframe(val){
    MainPage = decodeURI(top.location.href).toLowerCase().replace('null',val+'.aspx');
    MainPage = MainPage.replace('adminlogin.aspx',val+'.aspx');
    MainPage = MainPage.replace('candidatelogin.aspx',val+'.aspx');
    MainPage = MainPage.replace('admin.aspx',val+'.aspx');
    MainPage = MainPage.replace('candidate.aspx',val+'.aspx');//}
 
    //parent document is redirected to the exact page
    if(decodeURI(top.location.href).toLowerCase().indexOf(decodeURI(MainPage)) <0){
         //alert('placing in frame');
        top.location.href = MainPage;
    }
    setfp();//i set here or new win will not open in frame win
}


//this function is used to count the opened and closed windows so as to make sure when to call the session data clearing.
//i want to make sure the session clearing is only done when the user closes the last page.
function browserCount(type){
    if(type=='add'){
        cpc=getCookie('cpc');
        if(cpc==null || cpc <0){cpc=1;setck('cpc',cpc)}else{cpc=parseInt(cpc)+1;setck('cpc',cpc);}
    }
    else if(type=='minus'){
        
         if(document.getElementById('ContentFr').contentDocument){//firefox
            doc = document.getElementById('ContentFr').contentDocument;
            cpc=getCookie('cpc',document.getElementById('ContentFr').contentDocument);}//get child page count
        else{doc = document.frames['ContentFr'].document;//IE
                cpc=getCookie('cpc',document.frames['ContentFr'].document);}

        if(cpc==null || cpc <0){cpc=1;setck('cpc',cpc)}else{cpc=parseInt(cpc)-1;setck('cpc',cpc,doc);}
    }
        
    return cpc.toString();
}


//called in all pages which has topheader control.
//to make sure that no pages is taken directly.
//int loadcounter=0;
function isInframe2(val){

    //ppBlockCheck();

    //some browsers history starting length is 0 and some have 1.
    historyStart=0;
    if(getBrowser()=='firefox'){historyStart=1;}
    else {historyStart=0;}//i assume all other browsers will have history start length as 0. IE is having 0.

    //if the child page is in iframe, then exit the function here.
    if(window.top!=window){
        //the cookies that was set in the parent page is set into the child doc
        document.cookie = parent.document.cookie;
        
        //i saw some browsers(firefox) loads 2 time, if the child page is taken direcly in new page.
        //if a new page then there will be no history, when this page is load the history will be the initial value(0 or 1)
        if(history.length==historyStart){
            loadcounter=getCookie('loadcounter');
            //alert('loadcounter :' + loadcounter.toString());
            if(loadcounter==null || loadcounter <0){cpc=browserCount('add');}
        }
       setck('loadcounter',-1); 
       return 
    }
    
    //new page check.
    //when opened in a new page this gets fired and i count here the opened new pages count.
    //so when the last page is closed i can fire the session ending page to clear all session data.
    //if a new page then there will be no history, when this page is load the history will be the initial value(0 or 1)
    if(history.length==historyStart){
        cpc = browserCount('add');
        //alert(cpc.toString());
        //i mark here that new page loading is already counted and don't count if a second loading is happened.
        //sometimes if the child page is taken directly, the loading is happened 2 times.
        loadcounter = historyStart +1;
        setck('loadcounter',loadcounter);
    }
    
    var MainPage  = getCookie('fp');

    //Checks whether the address bar URL is adminlogin.aspx or candidatelogin.aspx, if sooo, this gets the page name admin.aspx and candidate.aspx
    //respectively.
    if(MainPage==null){
        MainPage = top.location.href.toLowerCase().replace('null',val+'.aspx');}
    //remove all the query strings
    MainPage = MainPage.replace(/\?.*$/,"");
    //if parent page is not frame then redirect to the frame page.
    //the currnt child page is also taken as the query string to load in the parent page frame.
    if(decodeURI(top.location.href).toLowerCase().indexOf(decodeURI(MainPage)) <0){
        top.location.href = MainPage+'?child='+top.location.href;
    }
}



//attaching event to all child pages via topheader to redirect F5 refresh to the child pages.
function disableF52(){
    this.document.onkeydown=function(){ disableF5(event);};
//if( this.document.attachEvent )//IE
//attachEvent(eventname, eventprocedure)
//else if( this.document.addEventListener )
//addEventListener(eventname, eventprocedure, false)
}



//loads iframe src here.
function loadChild(iframe, defaultpage){
    if(getURLInQueryString('child')){
        childpage = getURLInQueryString('child');
       iframe.src = childpage; 
    }
    else{
        iframe.src = defaultpage;
    }
    //this is required to make sure that the child page(in frame)is having focus always at the very beginning when a page is initially loaded.
    iframe.document.focus();
}


//i disabled F5 bcaz F5 from keyboard fires the parent load and unload event will be fired
//we just want to load the child page, so here i refresh the child page when a F5 is detected.
function disableF5(e){

    if(document.getElementById('ContentFr')){
        if(document.getElementById('ContentFr').contentDocument){//firefox
            doc = document.getElementById('ContentFr').contentDocument;}
        else{doc = document.frames['ContentFr'].document;}//IE
    }

	if (e.which && e.which == 116){//firefox
        e.preventDefault();
        //e.stopPropagation();
        
        //if focus in parent page then only do this reload(refresh)
        if ((decodeURI(location.href).toLowerCase().indexOf('public/admin.aspx')>=0) || (decodeURI(location.href).toLowerCase().indexOf('public/candidate.aspx')>=0)){
             doc.focus();
            doc.location.href = doc.location.href;//this does the same activitiy of F5
            }
        //if focus not in child page then only do this reload(refresh)
        else if ((decodeURI(location.href).toLowerCase().indexOf('public/admin.aspx')<0) && (decodeURI(location.href).toLowerCase().indexOf('public/candidate.aspx')<0))
            location.href=location.href;//this does the same activitiy of F5
    }
    else if (e.keyCode && e.keyCode == 116){//IE
        e.returnValue=false;
        e.keyCode=0;
        //e.cancelBubble = true
        
        //if focus in parent page then only do this reload(refresh)
         if ((decodeURI(location.href).toLowerCase().indexOf('public/admin.aspx')>=0) || (decodeURI(location.href).toLowerCase().indexOf('public/candidate.aspx')>=0)){
            doc.focus();
            doc.location.href = doc.location.href;//this does the same activitiy of F5
           }
        //if focus not in child page then only do this reload(refresh)   
        else if ((decodeURI(location.href).toLowerCase().indexOf('public/admin.aspx')<0) && (decodeURI(location.href).toLowerCase().indexOf('public/candidate.aspx')<0))
            location.href=location.href;//this does the same activitiy of F5
    }
}
    
    
//adjusts Iframe heights
function adjustIFrameSize (iframeWindow) {
   var docH = 0;
    docH=getDocHeight();
    
    if(document.getElementById(iframeWindow).contentDocument){
       document.getElementById(iframeWindow).height = docH ;
    }
    else{//IE
        document.getElementById(iframeWindow).style.height = docH ;
    }
}


//fires when closing of a parent page.
function closeAll(){

    if(document.getElementById('ContentFr').contentDocument){//firefox
        doc = document.getElementById('ContentFr').contentDocument;
        cpc=getCookie('cpc',document.getElementById('ContentFr').contentDocument);}//get child page count
    else{doc = document.frames['ContentFr'].document;//IE
            cpc=getCookie('cpc',document.frames['ContentFr'].document);}
        
    //if no child windows is opened
    if(cpc=="" || cpc==null || isNaN(cpc)){
        //document.getElementById('close').click();
        window.open('SA.aspx','','height=1px,width=1px,titlebar=no,menubar=no,status=no,scrollbar=no,location=no,top=0,left=0');setck('cpc','-1',doc);setck('pb',"",doc);
    }
        
    //when child windows are closed, i count the windows closed here.    
    cpc = browserCount('minus');
    //when child window is opened.
    //when the user closes the last window the count of that window will be mostly -1
    //when the user closes the last window then the IF clause is fired.
    if(cpc<0){
        //document.getElementById('close').click();
        window.open('SA.aspx','','height=1px,width=1px,titlebar=no,menubar=no,status=no,scrollbar=no,location=no,top=0,left=0');setck('cpc','-1',doc); setck('pb',"",doc);
    }
}
