﻿function sendAjaxMessage(message,query, callback)
{
    var xmlhttp = setupAjax();
    
    var handlerFunction = getReadyStateHandler(xmlhttp,callback)
    {
        callback(xmlhttp);
    }
    
    xmlhttp.onreadystatechange = handlerFunction;
    
    xmlhttp.open("GET","AjaxControl.aspx?msg="+message+query,true);
    xmlhttp.send(null);
}   

function submitEmailAddress()
{
    var email = document.getElementById('email').value;
    sendAjaxMessage("Newsletter","&email="+email,function (){alert('Thank you for your interest in our newsletter');});
}

var lastopened = readCookie('courselist');

function processCourseLists()
{
    //alert('loading last opened ' + lastopened);
    
    //Initialize first demo:
    ddaccordion.init({
	    headerclass: "departments", //Shared CSS class name of headers group
	    contentclass: "courses", //Shared CSS class name of contents group
	    revealtype: "click", //Reveal content when user clicks or onmouseover the header? Valid value: "click", "clickgo", or "mouseover"
	    mouseoverdelay: 200, //if revealtype="mouseover", set delay in milliseconds before header expands onMouseover
	    collapseprev: false, //Collapse previous content (so only one open at any time)? true/false 
	    defaultexpanded: [lastopened], //index of content(s) open by default [index1, index2, etc]. [] denotes no content.
	    onemustopen: false, //Specify whether at least one header should be open always (so never all headers closed)
	    animatedefault: false, //Should contents open by default be animated into view?
	    persiststate: false, //persist state of opened contents within browser session?
	    toggleclass: ["courseCollapsed", "courseOpen"], //Two CSS classes to be applied to the header when it's collapsed and expanded, respectively ["class1", "class2"]
	    togglehtml: ["none", "", ""], //Additional HTML added to the header when it's collapsed and expanded, respectively  ["position", "html1", "html2"] (see docs)
	    animatespeed: "fast", //speed of animation: integer in milliseconds (ie: 200), or keywords "fast", "normal", or "slow"
	    oninit:function(expandedindices){ //custom code to run when headers have initalized
		    //do nothing
	},
	onopenclose:function(header, index, state, isuseractivated){ //custom code to run whenever a header is opened or closed
		//do nothing
		
		if(isuseractivated)
		{
		    if(state == 'block')
		    {
		        lastopened = index;
		        createCookie('courselist',index,9);
		        //alert('Setting last opened '+lastopened);
		    }
		}
	}
    });
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function getReadyStateHandler(req, responseXmlHandler) {  
     // Return an anonymous function that listens to the   
     // XMLHttpRequest instance  
     return function () {  
     // If the request's status is "complete"  
         if (req.readyState == 4) {  
             // Check that a successful server response was received  
    
             if (req.status == 200) {                  //todo: catch 404 error.  
                 // Pass the XML payload of the response to the   
                 // handler function  
                 responseXmlHandler(req);  
             } 
         }  
     }  
 }       
            
function setupAjax()
{
    var xmlhttp;
    
    if (window.XMLHttpRequest)
    {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    else
    {
        alert("Your browser does not support XMLHTTP!");
    }
    
    return xmlhttp;
}

function addCourseAdditionalInfoBox(text)
{   
    var topText = text.substring(text.indexOf('<result>')+8,text.indexOf('</result>'));
    YUI().use('node', 'anim', function(Y) { 
        var contentNode = Y.Node.get('#content');
        var createNode = Y.Node.create('<div id="courseTextArea"><textarea id="AddInfo" name="AddInfo" cols="10" rows="5" style="opacity:0.0;filter:alpha(opacity=0);">'+topText+'</textarea></div>');
        var refNode = Y.Node.get('#courseTextArea');
        
        refNode.ancestor('*').replaceChild(createNode,refNode);
        
        var myAnim = new Y.Anim({ 
            node: '#courseTextArea', 
            from: {
                opacity: 0.0
            },
            to: { 
                opacity:1.0
            } 
        }); 
        
        myAnim.set('duration', 2.0); 
        myAnim.set('easing', Y.Easing.easeIn); 
        myAnim.run();
    });
    
    setTimeout ( 'processTextAreas();', 100);
}

function AdditionalInfoHandle (xmlhttp)
{
    if(xmlhttp.readyState==4)
    {
        // extract id and result
        
        var response = xmlhttp.responseText;
        
        var type = response.substring(response.indexOf('<type>')+6,response.indexOf('</type>'));
        
        if(type == 'TopText')
        {
            var topText = response.substring(response.indexOf('<result>')+8,response.indexOf('</result>'));
            
            // do some YUI stuff here to add the box or replace the box thats allready there
            addCourseAdditionalInfoBox(response);
        }     
        else if(type=='No data')
        {
            addCourseAdditionalInfoBox('No Data');
        }               
    }
}

function getAdditionalInfoBox()
{
    var coursetype= document.getElementById('CourseType').options[document.getElementById('CourseType').selectedIndex].value;
    
    sendAjaxMessage('GetTopText','&type='+coursetype,AdditionalInfoHandle);
}

function addSectionInContent(content)
{ 
    YUI().use('node', 'anim', function(Y) { 
        var contentNode = Y.Node.get('#content'); 
        var createNode = Y.Node.create('<div id="Inserted" style="opacity:0.0; filter:alpha(opacity=0);overflow:hidden;"><div class="box" style="width:100%; clear:both;">'+
	'<div class="boxTitle" style="height:40px; width:100%">'+
		'<div class="containerboxtitleleft" style="background-image:url(\'images/turq-left.png\');"></div>'+
		'<div class="containerboxtitlemiddle" style="width:671px; background-image:url(\'images/turq-middle.png\');">'+
			'<div style="position:relative;left:10px;"></div>'+
		'</div>'+
		'<div class="textonly"></div>'+
		'<div class="containerboxtitleright" style="background-image:url(\'images/turq-right.png\');"></div>'+
	'</div>'+
    '<div class="boxContent" style="height:50px;">'+
		'<div class="containerBoxContentLeft" style="height:50px;"></div>'+
		'<div class="containerBoxContent" style="width:669px;position:relative;">'+content+'</div>'+
		'<div class="containerBoxContentRight" style="height:50px;"></div>'+
	'</div>'+
	'<div class="boxFooter">'+
		'<div class="containerBoxFooterLeft" style="top:2px;"></div>'+
		'<div class="containerBoxFooterMiddle" style="top:2px; width:671px;"></div>'+
		'<div class="containerBoxFooterRight" style="top:2px;"></div>'+
	'</div>'+
'</div></div>');

    //var height1 = 87; 
    //createNode.get('.boxContent').setStyle('height',height1+'px'); 
                    
    if(contentNode.hasChildNodes())
    {
        var test = contentNode.get('children');
        test = test.item(2);
        test = test.get('children');
        test = test.item(0);

        if(test.nextSibling == null)
        {
            test.insertBefore(createNode,null);
            
            var height = createNode.get('.containerBoxContent').get('region').height;
            //alert(height);
            
            var insertedNode = Y.Node.get('#Inserted');
            
            //insertedNode.get('.boxContent').setStyle('height',(height)+'px');
            //insertedNode.get('.containerBoxContentLeft').setStyle('height',(height)+'px');
            //insertedNode.get('.containerBoxContentRight').setStyle('height',(height)+'px');
            //createNode.get('.containerBoxContentLeft').setStyle('height',height+'px'); 
            //createNode.get('.containerBoxContentRight').setStyle('height',height+'px'); 
            
            //alert(createNode.get('.containerBoxContentRight').get('region').height);
            
            
            var myAnim = new Y.Anim({ 
                node: '#Inserted',
                from: {
                    height: 0
                },
                to: { 
                    height: function(node) { return node.get('offsetHeight');  }
                } 
            }); 
            
            var myAnim2 = new Y.Anim({ 
                node: '#Inserted', 
                from: {
                    opacity: 0.0
                },
                to: { 
                    opacity:1.0
                } 
            }); 
            
            myAnim.set('duration', 1.0); 
            myAnim.set('easing', Y.Easing.easeOut); 
            myAnim.run();
            
            myAnim.on('end', function() { 
                myAnim2.set('duration', 1.0); 
                myAnim2.set('easing', Y.Easing.easeOut); 
                myAnim2.run();
            });
            
        }
    }
    });
    
    //setContainerBoxHeights();
}

function addLoadEvent(func2)
{
    //alert('addloadevent');
    var oldonload = window.onload;
    if(typeof window.onload != 'function')
    {
        window.onload = func2;
    }
    else
    {
        window.onload = function() {
            oldonload();
            func2();
        }
    }
}

function setContainerBoxHeight(box,value)
{
    setnodeheight = value;
    nodetoset = box;
    //alert('nodetoset set' + nodetoset);
    //box.firstChild.nextSibling.nextSibling.nextSibling.firstChild.nextSibling.style.height = value+'px';      
    //box.firstChild.nextSibling.nextSibling.nextSibling.firstChild.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.style.height = value+'px';
}

function getElementsByStyleClass ( className , element )
{
    //alert('getElementsByStyleClass');
    if ( element.hasChildNodes )
    {
        var all = element.getElementsByTagName('*');
        //alert(all.length);
        var elements = new Array();
        for( var e = 0; e < all.length; e++)
        {
            if(all[e].className == className)
            {
                //alert(className + ' Found');
                elements[elements.length] = all[e];
            }
            //elements.concat(getElementsByStyleClass('box',all[e]));
        }
        return elements;
    }
}

imageArray = new Array();

function addPreLoadImage( image )
{
    imageArray[imageArray.length] = image;
    //alert('adding image ' + imageArray.length);
}

function preLoadImages()
{
    for(var i=0; i<imageArray.length; i++)
    {
        preLoadImage = new Image();
        //alert('loading ' + imageArray[i]);
        preLoadImage.src = imageArray[i];
    }
}