/*
 *  GENERAL UTILITIES
 * @class Utils
 * @requires Page, document
 *
 * @methods
 *
 * -validateEmail
 * -preLoadImg (legacy)
 * -getURLComponents
 * -getXML (legacy)
 * -fillElement (legacy)
 * -fillString (legacy)
 * -flashWrite (legacy)
 * -calculateScreenWidth
 * -calculateScreenHeight
 * -calculateCenterX
 * -calculateCenterY
 * -getTime
 * -getUserTime
 * -isDSTinNorthAmerica
 * -isDSTinEurope 
 */ 

Utils = {

	validateEmail: function(obj){

        var val;

        (obj.val)? val = obj.val() : val = obj.value;

        val = val.toLowerCase();

        var regx = /\w{1,}@(\w{1,})\.(\w{1})/;

        return regx.test(val);

    },


	//preloads an image		

	 preLoadImg: function(url){

        var img = new Image();
        img.src = url;

     },

	//runs on page init, extracts URL components for later use
	
	getURLComponents: function(){

        Page.config.MODULE = Page.config.LOCATION.replace('http://'+Page.config.HOST, '');

        var urlComponents = Page.config.MODULE.split('/');

        Page.config.MODULE = urlComponents[1];
        Page.config.SECTION = urlComponents[2];
        Page.config.SUB_SECTION = urlComponents[3];

        if(Page.config.MODULE == '') Page.config.MODULE = 'home';

		var getArr = Page.config.QUERY_STRING.split('&');

        for(var i = 0; i<getArr.length; i++){

            var tempArr = getArr[i].split('=');

            Page.config.GET[tempArr[0]] = tempArr[1];

        }

    },

	/*  Legacy Function
 	*
 	*	@returns XMLHTTPRequest Object
 	*
 	*/

	getXML: function(){

        var xmlhttp=null;

        try {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {

            try {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                xmlhttp = new XMLHttpRequest();
            }
        }

        return xmlhttp;

    },

	/* Requests Ajax Data and fills an element with the responseText
 	 * @params 
 	 *	element - target element
     *  page - location to send the request
     *  vars - key/value pairs
     *  hide/show - elements to hide or show
     *  callback - a callback function to call after the request
     *  arg - arguements for the callback function
    */

	fillElement: function(element,page,vars,hide,show,callback,arg){

		var resp = true;

		$.ajax({

			url: page + "?ajax&"+vars,
			type: "post",
			
			success: function(data){
				
				try{
				
					if(element) $('#'+element).html(data);
					if(data == "") resp = false;
				
					if(hide) (resp)? $('#'+hide).show() : $('#'+hide).hide();

					if(show) (resp)? $('#'+show).hide() : $('#'+show).show();

					if(callback) callback(arg, resp, data, false);
			
				}catch(e){

					try {
                		
						if(callback) callback(arg,false,data,true);
             
            		} catch(e) {}

				}
			}

		});
	},

	/* Requests Ajax Data and calls a callback function with the data
 	 * @params 
 	 *  page - locaiton to send request 
 	 *  vars - key/value pairs
 	 *  callback - callback function
 	 *  arg - arguements for the calback function
 	*/

	fillString: function(page,vars,callback,arg){

		$.ajax({

			url: page + "?ajax&" + vars,
			type: "post",

			success: function(data){
				
				try{

					if(callback) callback(arg, data, false);

				}catch(e){

					try{
					
						if(callback) calback(arg, data, true);

					}catch(e){}

				}
			}

		});

	},

	/* FlashWrite (legacy)
     *  
     * @params
     * -url: The location of the file
     * -w: width
     * -h: height
     * -id: the id
     * -bg: Background color
     * -win: Transparent or not
     * -params: array of parameters [[param1, 1], [param2, 2]] (optional)
     */

	flashWrite: function(url,w,h,id,bg,win,params){

		var flashStr=
    				"<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0' width='"+w+"' height='"+h+"' id='"+id+"' align='middle'>"+
    				"<param name='movie' value='"+url+"' />"+
    				"<param name='wmode' value='"+win+"'>"+
    				"<param name='Menu' value='false'>"+
    				"<param name='quality' value='high'>"+
    				"<param name='bgcolor' value='"+bg+"' />";
					
					if(params){

						for(var i = 0; i<params.length; i++){

							flashStr += "<param name='" + params[i][0] + "' value='" + params[i][1] + "' />";				

						}

					}

    		flashStr += "<param name='allowScriptAccess' value='always'>"+
    				"<embed src='"+url+"' wmode='transparent' width='"+w+"' height='"+h+"' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer' ";

					if(params){

                        for(var i = 0; i<params.length; i++){

                            flashStr += params[i][0] + "='" + params[i][1]+"' ";

                        }

                    }


			flashStr += '></embed></object>';

 		document.write(flashStr);

	},

	// @returns window width

	calculateScreenWidth: function(){

        return $(window).width();

    },	

	// @returns window height
	
	calculateScreenHeight: function(){

        if(document.all){

            var h = $('body').height();

            if(h > $(window).height()){

                return h + 20;

            }else{

                return $(window).height();

            }

        }else{

            var h = $('html').height();

            if(h > $(window).height()){

                return $('html').height();

            }else{

                return $(window).height();

            }

        }

    },

	// @returns the X position that will center an object
	
	calculateCenterX: function(obj){

        return $(window).width()/2 - $(obj).width()/2;

    },

	// @returns the Y position that will center an object (adjusted to scroll top)
	
	calculateCenterY: function(obj){

		if($.browser.safari){

			return $('body').scrollTop() + ($(window).height()/2 - $(obj).height()/2);

		}else{

        	return $('html').scrollTop() + ($(window).height()/2 - $(obj).height()/2);

		}
    },

	/* @returns an associative array  based on the zone parameter
     * @params zone: possible values ('west', 'east', 'euro')
     */

	getTime: function(zone){

        var d = new Date();
        var t = [];

        var UTCHours = d.getUTCHours(); //get UTC hours

        switch(zone){

            case 'west':
                offset = 7;
                break;

            case 'east':
                offset = 4;
                break;

            case 'euro':
                offset = -2;
                break;

        }

        t['month'] = d.getMonth();
        t['day'] = d.getDay();
        t['date'] = d.getDate(); //day of the month 0 -31

        if(zone == 'euro'){

            (Utils.isDSTinEurope())? dst = 0  : dst = 1;

        }else{

            (Utils.isDSTinNorthAmerica())? dst = 0  : dst = 1;

        }

        var curHours = UTCHours - offset;

        if(curHours < 0) curHours = 24 + curHours;

		if(Page.language == 'en'){
        	(curHours + dst > 11 && curHours < 24)? ampm = 'pm' : ampm = 'am';

		}else{
			ampm = '';
		}

		if(Page.language == 'en'){

        	if(curHours < 0)  curHours = 24 + curHours;
        	if(curHours > 12) curHours = curHours - 12;

		}

		var q = curHours - dst; 

        if(Page.language == 'en' && q == 0) q = 12;
		if(Page.language != 'en' && q >= 24) q = q - 24;
        if(Page.language == 'en' && q == 13) q = 1;

        t['date'] = d.getDate(); //day of the month 0 -31
        t['hours'] = q;
        t['minutes'] = d.getMinutes();
        t['seconds'] = d.getSeconds();
		t['ampm'] = ampm;

        return t;

    },

	getUserTime: function(){

        var d = new Date();
        var t = [];
        t['hours'] = d.getHours();
        t['minutes'] = d.getMinutes();
        t['seconds'] = d.getSeconds();

		if(Page.language == 'en'){
        	(t['hours'] < 12)? t['ampm'] = 'am' : t['ampm'] = 'pm';
		}else{
			t['ampm'] = '';
		}        


		return t;

    },

	/* @returns true/false
     * Tests if it's daylight savings time in North America
     */

	 isDSTinNorthAmerica: function(){

		var dst = ['spring', 'fall'];
		var dstDates = [14, 13, 11, 10, 9, 8];
		var dstDates2 = [7, 6, 5, 4, 3, 2, 1];
		dst['spring'] = [];
		dst['fall'] = [];		

		var t = 0;
        var q = 0;
        for(var i=2001; i<2100; i++){

            t++;
            q++;

            dst['spring'][i] = dstDates[t];
            dst['fall'][i] = dstDates2[q];
            if(t == 5) t = 0;
            if(q == 6) q = 0;
        }	

        var d = new Date();
        var date = d.getDate();
        var day = d.getDay();
        var month = d.getMonth();
		
		if(month < 2 || month > 10){

			return false

		}else{


			if(month == 2 || month == 10){

				if(month == 2){
					
					if(date >= dst['spring'][d.getFullYear()]){

						return true;

					}else{
						
						return false;	

					}

				}else{

					if(date >= dst['fall'][d.getFullYear()]){

						return false;

					}else{

						return true;

					}

				}
				

			}else{

				return true;

			}

		}
    },

	/* @returns true/false
     * Tests if it's daylight savings time in Europe
     */
  
	isDSTinEurope: function(){

		var dst = ['spring', 'fall'];
        var dstDates = [25, 31, 30, 29, 28, 27];
        var dstDates2 = [28, 27, 26, 25, 31, 30];
        dst['spring'] = [];
        dst['fall'] = [];

        var t = 0;
        var q = 0;
		for(var i=2001; i<2100; i++){

            t++;
            q++;

            dst['spring'][i] = dstDates[t];
            dst['fall'][i] = dstDates2[t];
            if(t == 5) t = 0;
        }

        var d = new Date();
        var date = d.getDate();
        var day = d.getDay();
        var month = d.getMonth();


		if(month < 2 || month > 10){

            return false

        }else{


            if(month == 2 || month == 10){

                if(month == 2){

                    if(date >= dst['spring'][d.getFullYear()]){

                        return true;

                    }else{
                        
						return false;

                    }

                }else{

                    if(date >= dst['fall'][d.getFullYear()]){

                        return false;

                    }else{

                        return true;

                    }

                }


            }else{

                return true;

            }

        }

    }

}

