if (typeof(K) === "undefined") K = {};

/***********************************
 * UTILS
 ***********************************/

K.Utils = {
        loginToken : /^<!-- logintok:6039542760 -->/,

        initDatagridStyling: function (){
            $('table.datagrid tbody tr:odd').addClass('odd');
        },

	arrayContains: function(target, val){
		for (var i = 0; i < target.length; i++){
			if (target[i] === val) return i;
		}
		return -1;
	},

        arrayContainsObjectWithVal: function(target, val, key){
		for (var i = 0; i < target.length; i++){
			if (target[i][key] === val) return i;
		}
		return -1;
	},

	isEmptyTrim: function(str){
		return this.isEmpty($.trim(str));
	},

	isEmpty: function(){
             for (var i=0; i<arguments.length; i++) {
                 if (arguments[i] === '' || arguments[i] === undefined || arguments[i] === null){
                     return true;
                 }
             }
             return false;
	},

        combineObjects: function(objA, objB){
            var newObject = $.extend(true, {}, objB);
            for (var idx in objA){
                newObject[idx] = objA[idx];
            }
            return newObject;
        },

        unescapeHTML: function (html) {
             return $("<div />").html(html).text();
        },

        escapeHTML: function (html) {
             return $("<div />").text(html).html();
        },

        combineObjects: function(a, b){
            if (typeof(a) !== 'object' || typeof(b) !== 'object') return;

            var c = {};

            for(var idx in a){
                c[idx] = a[idx];
            }

            for(var idx in b){
                if (!c[idx]){
                    c[idx] = b[idx];
                }
            }

            return c;
        },

        defaultVal: function(value, defaultVal){
            if (value === null || value === undefined || value === '') return defaultVal;
            return value;
        },

        trueVal : function(bool, val){
            if (bool) return val;
            return undefined;
        },

        first : function(obj){
            for(var idx in obj) return obj[idx];
        },

        firstIdx : function(obj){
            for(var idx in obj) return idx;
        },

        keys : function(obj){
            var ret = [];
            for(var idx in obj) ret.push(idx);
            return ret;
        },

        startsWith : function (str, val){
            return (str.match("^"+val)==val)
        },

        endsWith : function(str, val){
            return (str.match(val+"$")==val);
        },

        rgb2hex : function(rgb) {
            if (rgb === 'transparent') return 'transparent';
            else if (rgb === '') return undefined;

            //check to see if the rgb is already in hex
            if (K.Utils.startsWith(rgb, '#') && rgb.length == 7) return rgb;

            var rgbMatch = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
            if (!rgbMatch) rgbMatch = rgb.match(/^rgba\((\d+),\s*(\d+),\s*(\d+),\s*(\d+)\)$/);

            function hex(x) {
                return ("0" + parseInt(x).toString(16)).slice(-2);
            }

            return "#" + hex(rgbMatch[1]) + hex(rgbMatch[2]) + hex(rgbMatch[3]);
        },

        formatCents : function(value){
            return "$" + ((value/100).toFixed(2));
        },

        formatPhone : function(phone) {
            if (K.Utils.isEmpty(phone))
                return phone;

            phone = phone.replace(/[^0-9]+/, '');
            phone = '(' + phone.substr(0, 3) + ') ' + phone.substr(3, 3) + '-' + phone.substr(6, 4);
            return phone;
        },

        buttonSpinner : function(selector, turnOn, message, replaceContents){
            if (turnOn){
                if (!message) message = 'Please wait...';

                var spinnerContainer = $('<span class="buttonSpinner" />');
                var spinner = $('<span class="buttonSpinnerMessage" style="font-size: 10px"><img src="/images/loading.gif" align="absmiddle" style="margin-right: 5px;" />' + message + "</span>");

                if (replaceContents){
                    $(selector).html('');
                    $(selector).append(spinnerContainer.append(spinner));
                }
                else {
                    $(selector).hide().wrap(spinnerContainer);
                    $(selector).parent('.buttonSpinner').append(spinner);
                }
            }
            else {
                if (replaceContents){
                    $(selector).find('.buttonSpinnerMessage').remove();
                }
                else {
                    $(selector).parent().find('.buttonSpinnerMessage').remove();
                    $(selector).unwrap().show();
                }
            }

        },

        launchHelp : function(){
            window.open("/help","Kishkee | Help", "menubar=no,width=1000,height=600,toolbar=no,scrollbars=1");
        },

        //these are just like jquery's but they check to see if the login session timed out
        get : function(url, data, callback, dataType){
            $.get(url, data, function(ret){
                if(ret.search(K.Utils.loginToken) == 0){
                    launchLogin();
                }
                if (dataType == 'json') ret = $.parseJSON(ret);
                callback(ret);
            }, 'text');
        },

        post : function(url, data, callback, dataType){
            $.post(url, data, function(ret){
                if(ret.search(K.Utils.loginToken) == 0){
                    launchLogin();
                }
                if (dataType == 'json') ret = $.parseJSON(ret);
                callback(ret);
            }, 'text');
        }

};


K.Utils.popupWindow = function(instanceSettings){
        //took this from jquery popup window plugin
        var defaultSettings = {
                centerBrowser:0, // center window over browser window? {1 (YES) or 0 (NO)}. overrides top and left
                centerScreen:0, // center window over entire screen? {1 (YES) or 0 (NO)}. overrides top and left
                height:500, // sets the height in pixels of the window.
                left:0, // left position when the window appears.
                location:0, // determines whether the address bar is displayed {1 (YES) or 0 (NO)}.
                menubar:0, // determines whether the menu bar is displayed {1 (YES) or 0 (NO)}.
                resizable:0, // whether the window can be resized {1 (YES) or 0 (NO)}. Can also be overloaded using resizable.
                scrollbars:0, // determines whether scrollbars appear on the window {1 (YES) or 0 (NO)}.
                status:0, // whether a status line appears at the bottom of the window {1 (YES) or 0 (NO)}.
                width:500, // sets the width in pixels of the window.
                windowName:null, // name of window set from the name attribute of the element that invokes the click
                windowURL:null, // url used for the popup
                top:0, // top position when the window appears.
                toolbar:0 // determines whether a toolbar (includes the forward and back buttons) is displayed {1 (YES) or 0 (NO)}.
        };

        settings = $.extend({}, defaultSettings, instanceSettings || {});

        var windowFeatures =    'height=' + settings.height +
                                        ',width=' + settings.width +
                                        ',toolbar=' + settings.toolbar +
                                        ',scrollbars=' + settings.scrollbars +
                                        ',status=' + settings.status +
                                        ',resizable=' + settings.resizable +
                                        ',location=' + settings.location +
                                        ',menuBar=' + settings.menubar;

        settings.windowName = this.name || settings.windowName;
        settings.windowURL = this.href || settings.windowURL;
        var centeredY,centeredX;

        if(settings.centerBrowser){

                if ($.browser.msie) {//hacked together for IE browsers
                        centeredY = (window.screenTop - 120) + ((((document.documentElement.clientHeight + 120)/2) - (settings.height/2)));
                        centeredX = window.screenLeft + ((((document.body.offsetWidth + 20)/2) - (settings.width/2)));
                }else{
                        centeredY = window.screenY + (((window.outerHeight/2) - (settings.height/2)));
                        centeredX = window.screenX + (((window.outerWidth/2) - (settings.width/2)));
                }
                window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
        }else if(settings.centerScreen){
                centeredY = (screen.height - settings.height)/2;
                centeredX = (screen.width - settings.width)/2;
                window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
        }else{
                window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + settings.left +',top=' + settings.top).focus();
        }
        return false;
}

Utils = K.Utils;

