/**
 * FIX IE6 IMAGE FLICKER PROBLEM
 *
 */
try {
	document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

$(document).ready(function() {
	Init();
});

function Init() {
	$("div.module h3.hdr-graphic").each(function(e) {
		this.onclick = function() {
			ToggleModule(this);
		};
	});
	
	$("#pg-home input.text").each(function(e) {
		this.onfocus = function() {
			ToggleInputText(this, true);
		};
		
		this.onblur = function() {
			ToggleInputText(this, false);
		}
	});
}

/**
 * Maximize/Minimize the modules windows that
 * appear in the "Notes" section.
 *
 */
function ToggleModule(e) {
try{
	$(e).siblings("div.box-inner").slideToggle('fast', function() {

		if($(e).parent().attr('class').indexOf('maximized') > -1) {
			$(e).parent().removeClass('maximized');
			$(e).parent().addClass('minimized');
		} else {
			$(e).parent().removeClass('minimized');
			$(e).parent().addClass('maximized');	
		}
		
	});
	}catch(e){}
}

/**
 * Hide/display helper text that
 * appears in the input fields.
 *
 */
function ToggleInputText(e, status) {
	if(status) {
		if(!e.initValue || e.initValue == $(e).val()) {
			e.initValue = $(e).val();
			$(e).val('');
		}		
	} else {
		if($(e).val().length < 1) {
			$(e).val(e.initValue);
		}
	}
}


//---------------------------------------------------------------------
// root object for web site
//---------------------------------------------------------------------
function $ge(obj){return document.getElementById(obj)}

var sn={

    // -----------------------------------------------------------------
    // FLASH BOX
    // -----------------------------------------------------------------
    flashbox:{
        pos:0,
        objs:[],
        effects:[
            {
                // this effect slides down from top then out to the right
                init:function(o){
                    o.style.cssText='vertical-align:center;width:160px;height:120px;top:-200px;left:10px;text-overflow:hidden;text-align:center;position:absolute'
                    $(o).show()
                   },
                fx:function(){sn.flashbox.effect1()},
                dom:{}
            },
            {
                // this effect slides up from the bottom the out to the left
                init:function(o){
                    o.style.cssText='vertical-align:middle;width:160px;top:200px;left:10px;height:120px;text-overflow:hidden;text-align:center;position:absolute'
                    $(o).show()
                    },
                fx:function(){sn.flashbox.effect2()},
                dom:{}
            },
            {
                // this effect makes the text huge and slowly scrolls it from right to left
                init:function(o){
                    o.style.cssText='line-height:auto;width:2000px;top:30px;height:120px;left:200px;vertical-align:middle;font-size:60px;position:absolute;'
                    $(o).show()
                    },
                fx:function(){sn.flashbox.effect3()},
                dom:{}
            },              
            {
                // this is the forth effect that fades in then changes color and fades out
                init:function(o){
                    o.style.cssText='text-overflow:hidden;text-align:center;line-height:auto;width:160px;top:10px;height:120px;left:10px;color:white;position:absolute;'
                    $(o).hide()
                    },
                fx:function(){sn.flashbox.effect4()},
                dom:{}
            }              
        ],
                        
        init:function(){
             sn.flashbox.setup()
        },
        setup:function(){
            if(document.getElementById('boxContent')){
            
                var els=document.getElementById('boxContent').childNodes
                sn.flashbox.pos=0
                if(els.length>0){
                    for(var x=0;x<els.length;x++){
                        if(els[x].nodeType == 1){
                            var theobj=new Object()
                            theobj.dom=els[x]
                            theobj.init=sn.flashbox.effects[sn.flashbox.pos].init
                            theobj.fx=sn.flashbox.effects[sn.flashbox.pos].fx
                            theobj.init(theobj.dom)
                            sn.flashbox.objs.push(theobj);
                            sn.flashbox.pos+=1
                            if(sn.flashbox.pos>3){sn.flashbox.pos=0}
                        }
                    }
                    document.getElementById('boxContent').style.display='block'                    
                    this.pos=-1
                    sn.flashbox.run()
                }else{
                    document.getElementById('boxContent').parentNode.style.display='none'
                }
            }
        },
        run:function(){
            if(sn.flashbox.pos!=-1){sn.flashbox.objs[sn.flashbox.pos].init(sn.flashbox.objs[sn.flashbox.pos].dom)}
            sn.flashbox.pos+=1;
            if(sn.flashbox.pos==sn.flashbox.objs.length){sn.flashbox.pos=0}
            //alert(this.pos)
            sn.flashbox.objs[sn.flashbox.pos].fx()
        },
        effect1:function(){
            var itm=sn.flashbox.objs[sn.flashbox.pos].dom
            step1()
            function step1(){$(itm).animate({top:'10px'},4000,'linear',function(){window.setTimeout(step2,3000)})}
            function step2(){$(itm).animate({left:'400px'},4000,'linear',step3)}                  
            function step3(){sn.flashbox.run()}
        },
        effect2:function(){
            var itm=sn.flashbox.objs[sn.flashbox.pos].dom
            step1()
            function step1(){$(itm).animate({top:'10px'},4000,'linear',function(){window.setTimeout(step2,3000)})}
            function step2(){$(itm).animate({left:'-200px'},4000,'linear',step3)}                  
            function step3(){sn.flashbox.run()}                
        },
        effect3:function(){
            var itm=sn.flashbox.objs[sn.flashbox.pos].dom
            step1()
            function step1(){$(itm).animate({left:'-2200px'},20000,'linear',step2)}
            function step2(){sn.flashbox.run()}                
        },
        effect4:function(){
            var itm=sn.flashbox.objs[sn.flashbox.pos].dom
            step1()
            function step1(){$(itm).fadeIn('slow',function(){window.setTimeout(step2,5000)})}
            function step2(){$(itm).fadeOut('slow',step3)}
            function step3(){sn.flashbox.run()}                
        }
    },
            
    // -----------------------------------------------------------------
    // SEARCH ROOT OBJECT   
    // -----------------------------------------------------------------
    search:{
        init:function(){
            clsCalendar($ge('frommaturity'),__LANG)
            clsCalendar($ge('tomaturity'),__LANG)
            clsCalendar($ge('fromissuedate'),__LANG)
            clsCalendar($ge('toissuedate'),__LANG)
        }
    },   // end search
    
    lasthpb:null,
    hpb:function(){
        var oHpbSelector=document.getElementById('hpbSelector');
        var oHistoricalGrid=document.getElementById('historicalGrid');
        
        if(sn.lasthpb!=null){
            sn.lasthpb.style.display='none';
        } 
        if(oHpbSelector.value=='-'){
            oHistoricalGrid.style.display='none';
        }else{
            sn.lasthpb=document.getElementById('hp'+oHpbSelector.value)
            sn.lasthpb.style.display='block'
            oHistoricalGrid.style.display='block';
        }
    },
    
    toString:function(){}
};

// base objects



function launchPopup(vURL,vName,vHeight,vWidth,vTop,vLeft) {
// Set default values if some arguments are omitted.
// The title of the pop-up window must be set in the <title></title>-clause of the pop-up.
if(vURL==null||vURL=="") return;
if(vName==null||vName=="") vName="modalPopUp";
if(vHeight==null||vHeight=="") vHeight="250";
if(vWidth==null||vWidth=="") vWidth="350";
if(vTop==null||vTop=="") vTop="200";
if(vLeft==null||vLeft=="") vLeft="200";
if ((navigator.appName.indexOf("Explorer") != -1) && (!window.opera)) {
var wpop=showModelessDialog(vURL, vName, "dialogHeight:" + vHeight + "px; dialogWidth:" + vWidth + "px; dialogLeft:" + vLeft + "px;dialogTop:" + vTop + "px");
} else {
var wpop=window.open(vURL, vName, "modal=1, height=" + vHeight + "px, width=" + vWidth + "px, left=" + vLeft + "px, top=" + vTop + "px");
wpop.focus();
}
}


//---------------------------------------------------------------------------
// CALENDAR OBJECT
//---------------------------------------------------------------------------
function clsCalendar(node, lang){
    var me=this;
    var __root={};                      // root dom element of control
    var __input={};                     // root input element under __root
    var __display={};                   // display dom element
    var __calendar={};                  // root calendar menu object
    var __dowEN=['S','M','T','W','T','F','S'];
    var __dowFR=['D','L','M','M','J','V','S'];
    
    var __moyEN=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    var __moyFR=['janv','fevr','mars','avril','mai','juin','juil','aout','sept','oct','nov','dec']
    
    var __days=new Array()              // dom pointer to calendar items
    var __activeDay={};                 // dom pointer to active date cell
    var __month={};                     // dom pointer to month drop down list
    var __year={};                      // dom pointer to year drop down list
    
    var __date=new Date()               // holds the active date
    var __suppliedDate=new Date()       // holds the date being rendered on the calendar
    
    var __displayed=false               // boolean indicating if cal displayed
    
    // private functions
    function init(){
        __root=node;
        __input=__root.getElementsByTagName('input')[0]
        
        __display=document.createElement('div')
        __display.className='content'
        __display.innerHTML=__input.value
        __display.onclick=toogleDisplay
        __display.onmouseout=rootOut
        __root.appendChild(__display)
        
        // create the root calendar object
        __calendar=document.createElement('div')
        __calendar.className='calendar'
        __calendar.onmouseout=calendarOut
        __root.appendChild(__calendar)
        
        // do some grid stuff
        createGrid()
        clearGrid()
        
        // now parse the existing date
        setDate()
        createMonth()
        createYear()
        createButtons()
        setGrid()
    }

    function createButtons(){
        var temp=document.createElement('img')
        temp.className="btn prevMonth"
        temp.src='_images/calendar/btn.previous.gif'
        temp.onclick=goPreviousMonth
        __calendar.appendChild(temp)
        
        var temp=document.createElement('img')
        temp.className="btn nextMonth"
        temp.src='_images/calendar/btn.next.gif'
        temp.onclick=goNextMonth
        __calendar.appendChild(temp)                
        
        var temp=document.createElement('div')
        temp.className="btn btnOK"
        temp.onclick=buttonOK
        temp.innerHTML='Ok'
        temp.onclick=buttonOK
        __calendar.appendChild(temp)          

        var temp=document.createElement('div')
        temp.className="btn btnClear"
        temp.onclick=buttonClear
        temp.innerHTML='clear'
        __calendar.appendChild(temp)                                     

        var temp=document.createElement('div')
        temp.className="btn btnCancel"
        temp.onclick=buttonCancel
        temp.innerHTML='cancel'
        __calendar.appendChild(temp)                                     
        
    }

    // parses the existing date which if not null
    // MUST BE yyyy-mm-yy
    function setDate(){
        if(__input.value.length!=0){
            var dateparts=__input.value.split('-')
            __suppliedDate=new Date(dateparts[0],dateparts[1]-1,dateparts[2])
        }else{
            __suppliedDate=new Date()
        }
        __date=new Date(__suppliedDate);
        __date.setDate(1)
    }
    
    function createMonth(){
        __month=document.createElement('select')
        __month.className='monthList'
        var monthArray=(lang=='en')?__moyEN:__moyFR;
        for(var lp=0;lp<monthArray.length;lp++){
            var opt=document.createElement('option')
            opt.value=lp
            opt.innerHTML=monthArray[lp]
            __month.appendChild(opt)
        }
        __month.onchange=onMonthChange
        __month.value=__date.getMonth()
        __calendar.appendChild(__month)    
    }
    function createYear(){
        var start=__date.getUTCFullYear()-10
        var end=__date.getUTCFullYear()+10
        var today=new Date()
        if(end<today.getYear()+10){end=today.getUTCFullYear()+10}
        __year=document.createElement('select')
        __year.className='yearList' 
        for(var lp=start;lp<=end;lp++){
            var opt=document.createElement('option')
            opt.value=lp
            opt.innerHTML=lp
            __year.appendChild(opt)
        }
        __year.onchange=onYearChange
        __year.value=__date.getUTCFullYear()
        __calendar.appendChild(__year)                                 
    }

    function createGrid(){
        var head=(lang=='en')?__dowEN:__dowFR;
        
        for(var rows=1;rows<=7;rows++){
            var classNameAppend=(rows==1)?' h':'';
            for(var cols=1;cols<=7;cols++){
                var obj=document.createElement('div')
                obj.className='c r'+rows+' c'+cols+classNameAppend
                if(rows==1){
                    obj.innerHTML=head[cols-1]
                }
                __days.push(__calendar.appendChild(obj))
            }
        }
    } // end create grid
    
    // clears the grid for a new month
    function clearGrid(){
        for(var lp=7;lp<__days.length;lp++){
            __days[lp].style.backgroundColor='#e6e6fa'
            __days[lp].style.cursor='default'
            __days[lp].innerHTML=''
            __days[lp].onmouseover=function(){}
            __days[lp].onmouseout=function(){}
            __days[lp].onclick=function(){}
        }
    }

    function setGrid(){
    
        // first clear the grid
        clearGrid()
        __activeDay={}

        // allways start at 7 on __days array to skip first row
        var dateInc=new Date(__date.getUTCFullYear(),__date.getUTCMonth(),1)
        var startPoint=dateInc.getUTCDay() 
        startPoint+=7
        var currentMonth=dateInc.getMonth()
        var currentDate=new Date()

        for(var lp=startPoint;lp<=__days.length;lp++){
            __days[lp].innerHTML=dateInc.getDate()
            __days[lp].style.cssText=''
            __days[lp].onmouseover=dayOver
            __days[lp].onmouseout=dayOff
            __days[lp].onclick=daySet
                
            if(dateInc.toDateString()==__suppliedDate.toDateString() ){
                __days[lp].style.backgroundColor='#f9d117'
                __activeDay=__days[lp]
            }
            if(dateInc.toDateString()==currentDate.toDateString() ){
                __days[lp].style.fontWeight='bold'
            }                    
            
            dateInc.setDate(dateInc.getDate()+1)
            
            if(dateInc.getMonth()!=currentMonth){
                break
            }                
        } // end for
        __month.value=currentMonth
        __year.value=__date.getYear()
    }

    //---------------------------------------------------------
    // methods
    var lastColor=''
    function dayOver(e){
        var obj=(window.event)?window.event.srcElement:e.target;
        if(__activeDay==obj){return}
        lastColor=obj.style.backgroundColor
        obj.style.backgroundColor='#fff0a6'
    }
    function dayOff(e){
        var obj=(window.event)?window.event.srcElement:e.target;
        if(__activeDay==obj){return}
        obj.style.backgroundColor=lastColor
    }
    function daySet(e){
        var obj=(window.event)?window.event.srcElement:e.target;
        __suppliedDate=new Date(__year.value,__month.value, obj.innerHTML)
        setGrid()
    }   
    function goPreviousMonth(){
        __date.setDate(1)
        __date.setMonth(__date.getMonth()-1)
        setGrid()
    }
    function goNextMonth(){
        __date.setDate(1)
        __date.setMonth(__date.getMonth()+1)
        setGrid()            
    }
    function buttonOK(){
        var m=new String(__suppliedDate.getUTCMonth()+1)
        var d=new String(__suppliedDate.getUTCDate())
        m=(m.length==1)?'0'+m:m;
        d=(d.length==1)?'0'+d:d;
        __display.innerHTML=__suppliedDate.getUTCFullYear() + '-' + m + '-' + d
        __input.value=__display.innerHTML
        show(false)
    }
    function buttonClear(){
        __display.innerHTML=''
        __input.value=''
        show(false)
    }
    function buttonCancel(){show(false)}
    function onMonthChange(){
        __date.setMonth(__month.value)
        setGrid()
    }
    function onYearChange(){
        __date.setYear(__year.value)
        setGrid()
    }
    function toogleDisplay(){
        if(__displayed){
            show(false)
        }else{
            show(true)
        }
    }
    function show(bol){
        __root.style.position=(bol)?'relative':'';
        __calendar.style.display=(bol)?'block':'none';
        __displayed=bol    
    }
    function calendarOut(e){
        try{
            var obj=(!e)?window.event.toElement:e.relatedTarget;
            if(obj==__calendar || obj.parentNode==__calendar){return}
            show(false)
        }catch(e){}
    }
    function rootOut(e){
        var obj=(!e)?window.event.toElement:e.relatedTarget;
        if(obj!=__calendar){show(false)}
    }
    
    init()
}

function textDefaulter(obj){
    var defaultVal=obj.value
    obj.onblur=function(){
        textDefaultBack(obj,defaultVal)
    }
    obj.value=''
}

function textDefaultBack(obj,defaultText){
    if(obj.value.length==0){obj.value=defaultText}
}


/*===========================================================*/
// AUTOSTART
/*===========================================================*/
if (window.attachEvent){ //IE exclusive method for binding an event
    window.attachEvent("onload", sn.flashbox.init)
}else{
    window.addEventListener("load", sn.flashbox.init, true)
}

