/*
* Modified by Jay Albano as of 2011.08.14
* - added the function postRemainingLength(referenceID, displayID, maxLength)
* -- for parsing the remaining characters available to type
*/
function trim(str) {
    var newstr = str.replace(/^\s*(.+?)\s*$/, "$1");
    if (newstr == " ") {
        return "";
    }
    return newstr;
}
function drop_spaces(str) {
    var newstr = trim(str);
    return newstr.replace(/(\s)+/g, ""); 
}
function check_email(email) {
    var template = /^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z])+$/;
    email = drop_spaces(email);
    if (template.test(email)) {
        return true;
    }
    return false; 
}
function array_key_exists (key, search) {
    return key in search;
}
function is_numeric (mixed_var) {
    return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') && mixed_var !== '' && !isNaN(mixed_var);
}
function strlen (string) {
    var str = string + '';
    var i = 0,
        chr = '',
        lgth = 0;

    if (!this.php_js || !this.php_js.ini || !this.php_js.ini['unicode.semantics'] || this.php_js.ini['unicode.semantics'].local_value.toLowerCase() !== 'on') {
        return string.length;
    }

    var getWholeChar = function (str, i) {
        var code = str.charCodeAt(i);
        var next = '',
            prev = '';
        if (0xD800 <= code && code <= 0xDBFF) { // High surrogate (could change last hex to 0xDB7F to treat high private surrogates as single characters)
            if (str.length <= (i + 1)) {
                throw 'High surrogate without following low surrogate';
            }
            next = str.charCodeAt(i + 1);
            if (0xDC00 > next || next > 0xDFFF) {
                throw 'High surrogate without following low surrogate';
            }
            return str.charAt(i) + str.charAt(i + 1);
        } else if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate
            if (i === 0) {
                throw 'Low surrogate without preceding high surrogate';
            }
            prev = str.charCodeAt(i - 1);
            if (0xD800 > prev || prev > 0xDBFF) { //(could change last hex to 0xDB7F to treat high private surrogates as single characters)
                throw 'Low surrogate without preceding high surrogate';
            }
            return false; // We can pass over low surrogates now as the second component in a pair which we have already processed
        }
        return str.charAt(i);
    };

    for (i = 0, lgth = 0; i < str.length; i++) {
        if ((chr = getWholeChar(str, i)) === false) {
            continue;
        } // Adapt this line at the top of any loop, passing in the whole string and the current iteration and returning a variable to represent the individual character; purpose is to treat the first part of a surrogate pair as the whole character and then ignore the second part
        lgth++;
    }
    return lgth;
}
function parseUri (str) {
    var    o   = parseUri.options,
        m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
        uri = {},
        i   = 14;

    while (i--) uri[o.key[i]] = m[i] || "";

    uri[o.q.name] = {};
    uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
        if ($1) uri[o.q.name][$1] = $2;
    });

    return uri;
};
function str_replace (search, replace, subject, count) {
    var i = 0,
        j = 0,
        temp = '',
        repl = '',
        sl = 0,
        fl = 0,
        f = [].concat(search),
        r = [].concat(replace),
        s = subject,
        ra = r instanceof Array,
        sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i = 0, sl = s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j = 0, fl = f.length; j < fl; j++) {
            temp = s[i] + '';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length - s[i].length) / f[j].length;
            }
        }
    }
    return sa ? s : s[0];
}
function ReloadComponent(uri_params, ajax_nav, ajax_nav_container, callback){
    uri_params = uri_params || '';
    ajax_nav = ajax_nav || '';
    ajax_nav_container = ajax_nav_container || '';
    callback = callback || function(){};
    
    $.post("/ajax.php?"+uri_params, { "action": "ajax_nav",  "PARAMS": {"AJAX_NAV" : ajax_nav} },
    function(Answer){
        $("#"+ajax_nav_container).fadeOut("fast", function() { $("#"+ajax_nav_container).html(Answer).fadeIn("fast", callback); } );
    }, "html");    
}
function controlHeight(tContentOut, tContentIn, bMainPage) {
    tContentOut = tContentOut || $("div.inter_content_out");
    tContentIn = tContentIn || $("div.inter_content_in");
    bMainPage = bMainPage || false;
    
    if(bMainPage == true) {
        if($("div.leftside").height() < $("div.rightside").height()) {
            $("div.leftside").height($("div.rightside").height());
        }
    }
    else {
        var marginBottomInter_content_out = str_replace('px', '', tContentOut.css("margin-bottom"));
        var heightRightSide = $("div.rightside").height();
        var heightMailptint = $("div.mailptint").height();
        var heightBanners_block = $("div.banners_block").height();
        
        var interContentOutNeedHeight = heightRightSide - heightMailptint - heightBanners_block - marginBottomInter_content_out;
        // tabs pages
        var heightTabs_box = $("div.tabs_box").height();
        interContentOutNeedHeight = interContentOutNeedHeight - heightTabs_box;
        //
        if(tContentIn.css("padding-bottom")) {
            var paddingBottomInter_content_in = str_replace('px', '', tContentIn.css("padding-bottom"));
        }
        else {
            var paddingBottomInter_content_in = 0;
        }
        if(tContentIn.css("padding-top")) {
            var paddingTopBottomInter_content_in = str_replace('px', '', tContentIn.css("padding-top"));
        }
        else {
            var paddingTopBottomInter_content_in = 0;
        }
        var interContentInNeedHeight = interContentOutNeedHeight - paddingBottomInter_content_in - paddingTopBottomInter_content_in;
        //tContentOut.css('min-height', interContentOutNeedHeight+'px');
        //tContentOut.css('height', 'auto !important');
        
        tContentIn.css('min-height', interContentInNeedHeight+'px');
        tContentIn.css('height', 'auto');    // important ?
    }
}
function alertSaved(omessageid, message) {
    message = message || 'The information in this section has been saved. Please save each additional section you are working on before leaving this page.';
    if(omessageid != '') {$('#'+omessageid).html(message);}
}
function changeTabs(id) {
    if(tab_changing != true) {
        var t = $("#"+id);
        tab_changing = true;
        var tidnew = t.attr("id");
        
        if($.browser.msie){
            $('#'+$("div.tabs_box").children("div.tab_on").children("a").attr("id")+'_content').hide();
            $("#"+tidnew+"_content").show();
            var t1 = $("#"+tidnew+"_content");
            var t2 = $("#"+tidnew+"_content div.inter_content_tabs");
            
            controlHeight(t1, t2);
            tab_changing = false;
        }
        else {
            $('#'+$("div.tabs_box").children("div.tab_on").children("a").attr("id")+'_content').fadeOut("fast",
                function() {
                    $("#"+tidnew+"_content").fadeIn("fast", function(){controlHeight($("#"+tidnew+"_content"), $("#"+tidnew+"_content div.inter_content_tabs"));});    //
                    tab_changing = false;
                }
            );
        }
        $("div.tabs_box").children("div").removeClass("tab_on").addClass("tab_off");
        t.parent("div.tab_off").toggleClass("tab_on");
        
        $("#headerEditButtonsControl").children().hide();
        
        $("#"+tidnew+"_HeaderEditButton").show();
    }
}
function InitSelect(id, value, text) {
    $("#"+id).val(value);
    $("#"+id+"_TEXT").text(text);
}
function maxlengthTA(id, c){
    var t = document.getElementById(id);
    var strMsg = t.value;
    var strMsgMax = strMsg.substring(0, c);
    var strMsgLen = strMsg.length;
    if(strMsgLen > c){t.value = strMsgMax;}
}
function postRemainingLength(referenceID, displayID, maxLength) {
    var postValue = document.getElementById(referenceID).value;
    var lengthLeft = maxLength - postValue.length;
    
    $("#" + displayID).text(lengthLeft);
}
function strpos(haystack, needle, offset) {
    var i = (haystack + '').indexOf(needle, (offset || 0));
    return i === -1 ? false : i;
}
function controlHeightMP() {
    controlHeight('', '', true);
} 
function serialize (mixed_value) {
    
    var _utf8Size = function (str) {
        var size = 0,
            i = 0,
            l = str.length,
            code = '';
        for (i = 0; i < l; i++) {
            code = str.charCodeAt(i);
            if (code < 0x0080) {
                size += 1;
            } else if (code < 0x0800) {
                size += 2;
            } else {
                size += 3;
            }
        }
        return size;
    };
    var _getType = function (inp) {
        var type = typeof inp,
            match;
        var key;

        if (type === 'object' && !inp) {
            return 'null';
        }
        if (type === "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            match = cons.match(/(\w+)\(/);
            if (match) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';

    switch (type) {
    case "function":
        val = "";
        break;
    case "boolean":
        val = "b:" + (mixed_value ? "1" : "0");
        break;
    case "number":
        val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
        break;
    case "string":
        val = "s:" + _utf8Size(mixed_value) + ":\"" + mixed_value + "\"";
        break;
    case "array":
    case "object":
        val = "a";
/*
            if (type == "object") {
                var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {
                    return;
                }
                objname[1] = this.serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }
            */
        var count = 0;
        var vals = "";
        var okey;
        var key;
        for (key in mixed_value) {
            if (mixed_value.hasOwnProperty(key)) {
                ktype = _getType(mixed_value[key]);
                if (ktype === "function") {
                    continue;
                }

                okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
                vals += this.serialize(okey) + this.serialize(mixed_value[key]);
                count++;
            }
        }
        val += ":" + count + ":{" + vals + "}";
        break;
    case "undefined":
        // Fall-through
    default:
        // if the JS object has a property which contains a null value, the string cannot be unserialized by PHP
        val = "N";
        break;
    }
    if (type !== "object" && type !== "array") {
        val += ";";
    }
    return val;
}
function check_passwords(password_id, password_confirm_id) {
	var PWD = $("#"+password_id).val();
	var CONFIRM_PWD = $("#"+password_confirm_id).val();
	
	if(strlen(PWD) < 6) {
		$("#PIC").show();
		$("#PC").hide();
	}
	else {
		$("#PIC").hide();
		$("#PC").show();
	}
	if(CONFIRM_PWD != PWD) {
		$("#PCIC").show();
		$("#PCC").hide();
	}
	else {
		$("#PCIC").hide();
		$("#PCC").show();
	}
}
