/*
 * General Utilities
 * @class Utils
 * @version 2.0
 * @requires document, jQuery
 */ 


if(!Utils) var Utils = {};

/* @description Utils.model are methods used primarily by internals
 */

Utils.model = {

	/* @description extends the inheritance chain of an existing object with another object
 	 * @params
 	 * newObj - the object that will be extended
 	 * oldObj - the object which will serve as the parent class
 	 */	 

	extend: function(newObj, oldObj){

        newObj.prototype = new oldObj();

    },

	/* @description makes an object read-only
 	 */ 

	freeze: function(obj){

        if(Object.freeze) Object.freeze(obj);

    },

	/* @description removes the ability to delete or add new properties/methods to an object
 	 */ 

    seal: function(obj){

        if(Object.seal) Object.seal(obj);

    }

}

/* @description Utils.forms are methods related primarily to form validation
 */

Utils.forms = {

	/* @description returns true or false based on if the value of the object is a valid email
 	 */ 

	validateEmail: function(input){

            var val, regx = /([\w{1,64}])@(\w{1,254})\.(\w{2,4})/g;

			if(typeof input == 'string') return regx.test($.trim(input.toLowerCase()));

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

            val = $.trim(val.toLowerCase());

            return regx.test(val);

     },

	/* @description returns true if an input value is greater or equal to beg and optionally less than end
	 * @params
	 * input - form input
	 * beg - beginning length
	 * end - ending length (optional)
	 */

	range: function(input, beg, end){

		var val;

		if(typeof input == 'string'){

			val = input;

		}else{

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

		}

		if(end){

			if(val.length >= beg && val.length < end) return true;

			return false;

		}else{

			if(val.length >= beg) return true;
			
			return false;

		}

	},

	/* @description checks if a value is numeric
 	 */

	isNumeric: function(input){

		var val;

		if(typeof input == 'string') return !isNaN(input);
	
        input.val ? val = $.trim(input.val()) : val = $.trim(input.value);

		return !isNaN(val);
		
	},

	/* @description checks if the value is entirely alphabetic
    */

	isAlphabetic: function(input){

		var val, regx = /[^A-z]/g;

		if(typeof input == 'string') return !regx.test(input);

		input.val ? val = $.trim(input.val()) : val = $.trim(input.value);

		return !regx.test(val);

	},

	/* @description checks if the value has a letter
    */

	hasLetters: function(input){

		var val, regx = /[A-z]/g;

		if(typeof input == 'string') return regx.test(input);

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

        return regx.test(val);

	},

	/* @description checks if a value contains numbers
     */

	hasNumbers: function(input){

		var val, regx = /\d/g;
        
		if(typeof input == 'string') return regx.test(input);

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

		return regx.test(val);

	},

    /* @description checks if a value has special characters
    */

	hasSpecialCharacters: function(input){

		var val, regx = /\W/g;

		if(typeof input == 'string') return regx.test(input);

        input.val ? val = $.trim(input.val()) : val = $.trim(input.value);

		return regx.test(val);	

	},

	/* @checks to see if a value exists
    */

	hasValue: function(input){

		var val, regx = /\w|\W/g;

		if(typeof input == 'string') return regx.test(input);

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

		return regx.test(val);	
		
	},

	/* @checks to see if two values match
    */

	match: function(input1, input2){

		var val1, val2;

		if(typeof input1 == 'string'){

			val1 = input1;

		}else{

			input1.val ? val1 = input1.val() : val1 = input1.value;

		}

		if(typeof input2 == 'string'){

			val2 = input2;

		}else{

			input2.val ? val2 = input2.val() : val2 = input2.value;

		}

		return val1 == val2;

	}

}

/* @description Utils.ajax contains methods that use ajax
 */

Utils.ajax = {

	/* [LEGACY] 
 	 * @description 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) {}

                }
            }

        });
    },

	/* [LEGACY]
     * @description 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 - arguments 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){}

                }
            }

        });

    }

}

Utils.general = {
	
	/* [LEGACY]
     * @description Writes a flash object to the page
     * @params
     * url - The location of the file
     * w - width
     * h - height
     * id - the id
     * bg - background color
     * win - transparent or opaque
     * 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);

    }

}

Utils.UI = {

	/* @description returns current screen width
 	 */  

	calculateScreenWidth: function(){

        return $(window).width();

    },

	/* @description returns total height of page
    */

	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();

            }

        }

    },

	/* @description returns x coordinate that would center an object on the screen
    */

	calculateCenterX: function(obj){

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

    },

	/* @description returns y coordinate that would center an object on the screen
    */

	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);

        }
    }

}

Utils.time = {

	 /* @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;

    },

	/* @description returns an associative array containing the users current time on their client
     */

	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;

    },

	/* @description returns true or false depending on 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;

            }

        }
    },

	/* @description returns true or false depending on 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 > 9){

            return false

        }else{


            if(month == 2){

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

                    return true;

                }else{
                    
                    return false;

                }

            }else if (month == 9){

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

                    return false;

                }else{

                    return true;

                }

            }else{

                return true;

            }

        }

    }
}
 
/* Legacy Backwards-Compatibility */

Utils.fillElement = Utils.ajax.fillElement;
Utils.fillString = Utils.ajax.fillString;
Utils.flashWrite = Utils.general.flashWrite;
Utils.calculateScreenWidth = Utils.UI.calculateScreenWidth;
Utils.calculateScreenHeight = Utils.UI.calculateScreenHeight;
Utils.calculateCenterX = Utils.UI.calculateCenterX;
Utils.calculateCenterY = Utils.UI.calculateCenterY;
Utils.getTime = Utils.time.getTime;
Utils.getUserTime = Utils.time.getUserTime;
Utils.isDSTinNorthAmerica = Utils.time.isDSTinNorthAmerica;
Utils.isDSTinEurope = Utils.time.isDSTinEurope;
 

