(function($){
    $.fn.initGridView = function(p) {
        this.each( function() {
            $(".toolbar span", this).hover(function(){
                $(this).addClass("hover");
            }, function(){
                $(this).removeClass("hover");
            });
            var cnt = 0;
            $(".gridview tr", this).each(function(){
                if ($(this).attr("norow") === null || $(this).attr("norow") != "false") {
                    if (++cnt%2){
                        $(this).addClass("odd");
                    } else {
                        $(this).addClass("even");
                    }
                }
                $(this).hover(function(){
                    $(this).addClass("hover");
                }, function(){
                    $(this).removeClass("hover");
                });
                if ($("th", this).size() > 0) {
                    $("th:last", this).css("border-right", "none");
                } else if ($("td", this).size() > 0) {
                    $("td:last", this).css("border-right", "none");
                }
            });
        });
    };
    $.fn.submitForm = function() {
        $("form", this).submit();
    };
})(jQuery);

var Utils = Utils || {};

Utils.FormList = Utils.FormList || {};

Utils.FormList.init = function(className) {
    if (typeof(className) == 'undefined') {
        className = 'form_list'
    }
    
    Utils.FormList.Buttons.Delete = $(".form_list #delete");
    Utils.FormList.Buttons.Update = $(".form_list #update");
}

Utils.popup = function(file, properties, name) {
    if (typeof(properties) == 'undefined') {
        properties = "titlebar=0,resizable=yes,width=800,height=540,status=1";
    }
    if (typeof(name) == 'undefined') {
        name = 'select_contents';
    }
    var popupWindow=open(file, name, properties);
    popupWindow.focus();
    
    return popupWindow;
}

Utils.popupImg = function(file, properties, name) {
    if (typeof(properties) == 'undefined') {
        properties = "titlebar=0,resizable=yes,width=620,height=460,status=1";
    }
    if (typeof(name) == 'undefined') {
        name = 'select_img';
    }
    return Utils.popup(file, properties, name);
}

Utils.Form = Utils.Form || {};
Utils.Form.create = function(formAction) {
    this.form = document.createElement('form');	
    document.body.appendChild(this.form ); 
    
    this.setTarget = function( target ){ this.form.target = target; }
    this.getTarget = function(){ return this.form.target; }        
    this.setName = function( name ){ this.form.name = name; }
    this.getName = function(){ return this.form.name; }
    this.setMethod = function( method ){	this.form.method = method;	}
    this.getMethod = function(){	return this.form.method;	}
    this.setAction = function( action ){ this.form.action = action ; }
    this.getAction = function(){ return this.form.action; }
    this.addInput = function( type, name, value){
        var input = document.createElement("input");
        input.setAttribute("type", type);
        input.setAttribute("name", name);
        input.setAttribute("value", value);
        this.form.appendChild(input);
    }
    this.submit = function(){ this.form.submit(); }
    
    if (typeof(formAction) != 'undefined') {
        this.getAction(formAction);
    }
    return this;
}

Utils.Form.getElementValue = function (el, form) {
    // 
    if (typeof(el) != 'object') {
        if (typeof(form) == 'undefined') {
            form = document.forms[0];
        } else if (typeof(form) != 'object') {
            form = document.forms[form];
        }
        if (typeof(form) != 'object') {
            return null;
        }
        eval("el = form."+el+";");
    }
    
    form = el.form;
    
    var values = [];
    if (typeof(el.length) != 'undefined' || el.type == 'checkbox' || el.type == 'radio') {
        if (el.type == 'checkbox' || el.type == 'radio') {
            eval("el = form.elements[\""+el.name+"\"];");
        }
        for (i = 0; i < el.length; i++){
            if (el[i].checked == true) {
                values.push(el[i].value);
            }
        }
    } else if (el.type == 'select') {
        if (el.options.length > 0) {            
            var selected_index = (el.selectedIndex > 0) ? el.selectedIndex : 0;
            values.push(el.options[selected_index].value);
        }
    } else if (el.type == 'select-multiple') {
        for (i = 0; i < el.options.length; i++){
            if (el.options[i].selected == true) {
                values.push(el.options[i].value);
            }
        }
    } else {
        values.push(el.value);
    }
    if (values.length == 0) {
        return null;
    } else if (values.length == 1) {
        return values.pop();
    }
    return values
}

Utils.Form.getVars = function (form) {
    if (typeof(form) == 'undefined') {
        form = document.forms[0];
    } else if (typeof(form) != 'object') {
        form = document.forms[form];
    }
    
    if (typeof(form) != 'object' || typeof(form.elements) == 'undefined') {
        return null;
    }
    
    var vars = []; 

    for (var i = 0; i < form.elements.length; i++) {
        var el = form.elements[i];

        if (!el.disabled && el.name) {
            if (el.name.match(/[\w]+\[[\w\[\]]*\]$/)) {
                var name = el.name.substr(0, el.name.indexOf("["));
                var els = el.name.match(/\[[\w]*\]/g);

                els.reverse();
                if (typeof(vars[name]) != 'object') {
                    vars[name] = [];
                }

                var tmp = 'vars["'+name+'"]';
                var index = 0;
                var len = els.length;
                while(index < len-1) {
                    var cur = els.pop();
                    cur = cur.substr(1, cur.length -2);                    
                    tmp += '["'+cur+'"]';
                    eval("var test = "+tmp+";");
                    if (typeof(test) == 'undefined') {
                        eval(tmp+" = [];");
                    }
                    index++;
                }
                
                var last = els.pop();
                last = last.substr(1, last.length -2);
                if (last !="") {
                    eval(tmp+"[\""+last+"\"]=Utils.Form.getElementValue(el);");
                } else {
                    var el_var = Utils.Form.getElementValue(el);
                    if (typeof(el_var) == 'object' || el.type == 'checkbox' || el.type == 'radio') {
                        eval(tmp+"=el_var;");
                    } else {
                        eval(tmp+".push(el_var);");
                    }
                }
            } else {
                vars[el.name] = Utils.Form.getElementValue(el);
            }            
        }
    }
    return vars;
}

Utils.Form.getVar = function (name, form) {
    var vars = Utils.Form.getVars(form);
    if (typeof(vars[name]) != 'undefined') {
        return vars[name];
    }
    return null;
}

Utils.submitTo = function(action, vars, method) {
    if (typeof(action) == 'object') {
        var form = action;
        form.addInput = function( type, name, value){
            var input = document.createElement("input");
            input.setAttribute("type", type);
            input.setAttribute("name", name);
            input.setAttribute("value", value);
            form.appendChild(input);
        }
        if (typeof(vars) == 'string') {
            form.action = vars;
        }
    } else {
        var form = Utils.Form.create();
        if (typeof(method) == 'undefined') {
            method = 'post';
        }
        form.setMethod(method);
        form.setAction(action);
    }
    if (typeof(vars) == 'object') {
        for (var i in vars) {
            if (typeof(vars[i]) == 'object') {
                for (var j in vars[i]) {
                    if (typeof(vars[i][j]) != 'object') {
                        var name = i + "[" + j + "]";
                        form.addInput('hidden', name, vars[i][j]);
                    }
                }
            } else {
                form.addInput('hidden', i, vars[i]);
            }
        }
    }
    form.submit();
}

Utils.Ajax = Utils.Ajax || {};
Utils.Ajax.submitTo = function (action, vars, callback, onError)
{
    jQuery.ajax({
        type: 'post',
        url: action,
        data: vars,
        dataType: 'json',
        success: function(data){            
            if (callback) {
                callback(data);
            }
        },
        error: function(data) { try { if (onError) onError(data); } catch (e) {} }
    });
}

Utils.goTo = function(action, vars) {
    Utils.submitTo(action, vars, 'get');
}

Utils.initGridView = function(id) {
	return $.initFlexGrid(id);
}

String.prototype.ucFirst = function()
{
//    return this.substr(0, 1).toUpperCase() + this.substr(1, this.length-1);
}


var Popup = Popup || {};
Popup.open = function(file, properties, name) {
    Utils.popup(file, properties, name);
}
Popup.callback = null;
Popup.closeback = null;
Popup.canSendback = function()
{
    if (Popup.callback != null && ((document.all && typeof(Media.callback) == 'object') || (!document.all && typeof(Popup.callback) == 'function'))) {
        return true;
    }
    return false;
}

Popup.sendback = function (o)
{
    // validate here

    // check and execute send callback
    if (Popup.canSendback()) {
        try {
            Popup.callback(o);
        } catch (e) {
            Popup.close();
        }
    }
    Popup.close();
}
Popup.close = function()
{
    var close = true;
    if (Popup.closeback != null && ((document.all && typeof(Popup.closeback) == 'object') || (!document.all && typeof(Popup.closeback) == 'function'))) {
        close = Popup.closeback();
    }
    if (close) {
        try {
            window.close();
        } catch (e) {
            throw Exception("Can not close current popup window.");
        }
    }
}

// jQuery utils



var Tabs = function (){
    return {
        display: function(tab_id, panel_id, group_id) {
            if (typeof(group_id) != 'undefined') {
                var group_selector = "#"+group_id;
                group_id = $(group_selector);
            } else {
                group_id = null;
            }
//            group_id = null;
            var tab_selector = ".tabs #"+tab_id;
            var panel_selector = ".panel_wrapper > #"+panel_id;
            $(".tabs li", group_id).removeClass("current");
            $(tab_selector, group_id).addClass("current");
            
            $(".panel_wrapper > div", group_id).removeClass("current");
            $(panel_selector, group_id).addClass("current");
        }
    }
}();

/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/
 
var Url = {
 
	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},
 
	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}
