﻿var SYSTEM_CONFIG = {
    CliWidth: $(document).width(), //800,
    CliHeight: $(document).height(), //600,
    CookieOpt: { expires: 365, path: "/" }, //cookie  period
    Language: 'en'
}
//, { 't': '日本語', 'v': 'ja' }
var __lang = [{ 't': 'English', 'v': 'en-US' }, { 't': 'Français', 'v': 'fr-FR' }, { 't': 'Deutsch', 'v': 'de-DE' }, { 't': 'Español', 'v': 'es' }, { 't': '中文(简)', 'v': 'zh-CN'}];

function setUI() {

    //    SYSTEM_CONFIG.CliWidth = $(window).width();
    //    SYSTEM_CONFIG.CliHeight = $(window).height();

    if (!SYSTEM_CONFIG.home) {
        SYSTEM_CONFIG = $.extend({ home: '' }, SYSTEM_CONFIG);
    }

    //scroll-x
    if (SYSTEM_CONFIG.CliWidth > 868) $('html').css('overflow-x', 'hidden');

    //set language
    setLanguage();

    //set menu
    setMenus();

    //set sub search
    setSubSearchEvent();

    //set png
    //fixPng();

    //set main
    //adjustMain();

    //Set LaodMask
    adjustLoad();

    //set miniCar
    //adjustMiniCar();

    setInputFoucs();

    //mac
    if (navigator.platform.toLowerCase().indexOf('mac') != -1) {
        loadCss("../images/css/mac.css");
    }
}


/*
* set loading
*/
function setLoading(b) {

    var tp = (SYSTEM_CONFIG.CliHeight - parseInt($('#loadMask').height())) / 2 + document.documentElement.scrollTop;

    $('#loadMask').css('top', tp);

    if (b) $('#loadMask').show();
    else $('#loadMask').hide();
}
function setLanguage() {
    var l = $.cookie('ptg_user_lang');
    SYSTEM_CONFIG.Language = (l) ? l : 'en-US';
    $.cookie('ptg_user_lang', null); //clear all
    $.cookie('ptg_user_lang', SYSTEM_CONFIG.Language, SYSTEM_CONFIG.CookieOpt);
    $('#hidLang').val(SYSTEM_CONFIG.Language);

    var lu = $('.lang .bd ul');
    $(__lang).each(function(i, o) { if (o.v == SYSTEM_CONFIG.Language) $('.lang .hd').text(o.t); ; lu.append("<li v='" + o.v + "'>" + o.t + "</li>"); });

    $('.lang').hover(function() {
        $(this).addClass('lango');
        $('.bd', $(this)).css('z-index', $('.hd', $(this)).css('z-index') - 1).show();
    }, function() {
        $('.bd', $(this)).hide().parent().removeClass('lango');
    });
    $('.lang .bd li').hover(function() { $(this).addClass('o'); }, function() { $(this).removeClass('o'); })
        .click(function() {
            var v = $(this).attr('v');
            if (v == 'zh-CN') { window.location.href = 'http://www.ptgcn.com'; return; }
            SYSTEM_CONFIG.Language = v;
            $.cookie('ptg_user_lang', SYSTEM_CONFIG.Language, SYSTEM_CONFIG.CookieOpt);
            var p = $(this).parent().parent(); p.hide();
            p.prev().text($(this).text());
            window.location = window.location;
        });
}
function setMenus() {
    $('.menu').each(function(i, m) {
        $(m).hover(function() {
            $(this).addClass('mover').parent().css('margin-right', -2);
            $('.menu-bd', $(this)).css('z-index', $('.menu-hd', $(this)).css('z-index') - 1).show();

        }, function() {
            $('.menu-bd', $(this)).hide().parent().removeClass('mover');
            $(this).parent().css('margin-right', 7);
        });
    });
}
function setSubSearchEvent() {
    $('#dvNavigationa .search').focus(function() { var o = $(this); if (o.val().Trim().toLowerCase() == 'product search') { o.val('') } else this.select(); })
    .blur(function() { if ($(this).val() == '') { $(this).val('Product Search'); $('.navsearchgo').attr('disabled', true); } else $('.navsearchgo').removeAttr('disabled') })
    .keydown(function(e) { var currentKey = e ? e.keyCode : e.which; if (currentKey == 13) { $('#dvNavigationa .searchGo').click(); return false; } });
}

//UserFrom
function userFrom(callback) {
    $.getJSON("../Handler/SystemHandler.ashx?r=" + Math.random(),
    { func: 'GetUserFrom' },
    function(res) {
        if (res && res.table[0].rows.length > 0) {
            $.cookie('ptg_user_web_from', res.table[0].rows[0]);
        }

        if (callback) callback(getCountry());
    });
}

//UserLogin
function runLoginIn() { }
function runLoginOut() { }
function getCountry() {
    //1. from cookie
    var countrySelected = $.cookie('ptg_user_country_selected');
    //2. from login info
    if (countrySelected == null && $.cookie('ptg_user_info_login') != null)
        countrySelected = $.cookie('ptg_user_info_login').Country;
    //3. from page response
    if (countrySelected == null && $.cookie('ptg_user_web_from') != null)
        countrySelected = $.cookie('ptg_user_web_from').CountryName;

    return countrySelected;
}

function adjustLoad() {
    var lf = (SYSTEM_CONFIG.CliWidth - parseInt($('#loadMask').width())) / 2;
    var tp = (SYSTEM_CONFIG.CliHeight - parseInt($('#loadMask').height())) / 2;
    $('#loadMask').css('left', lf).css('top', tp);
}

function adjustMain(h) {
    var hf = window.location.href;
    if ((hf.indexOf("Default.aspx") > 0 && hf.indexOf("ReturnUrl") < 0)) return;

    if (h) { $("#right_col").css('min-height', h); return; }

    //right
    var hr = $("#mcontent")[0].offsetHeight;

    var hl = parseInt($("#left_col")[0].offsetHeight);
    $("#right_col").css('height', Math.max(hl, hr));
}
function TuneIfrme(frm) {
    var fid = frm.id;
    var subWeb = document.frames ? document.frames[fid].document : frm.contentDocument;
    if (frm != null && subWeb != null) {
        frm.height = subWeb.body.scrollHeight;
    }
}
function setInputFoucs() {
    if ($.browser.msie) { $('input.t').each(function(i) { $(this).focus(function() { $(this).addClass('f'); }).blur(function() { $(this).removeClass('f'); }) }); }
}
//get Resquest
function getRequest(item) {
    var svalue = location.search.match(new RegExp("[\?\&]" + item + "=([^\&]*)(\&?)", "i"));
    return svalue ? svalue[1] : svalue;
}

function buildQueryStr(p) { var q = ""; for (var i = 0; i < p.length; i++) { q = q + (i > 0 ? "&" : "") + escape(p[i].name) + "=" + escape(p[i].value); } return q; }

String.prototype.Trim = function() { return this.replace(/(^\s*)|(\s*$)/g, ""); }
String.prototype.LTrim = function() { return this.replace(/(^\s*)/g, ""); }
String.prototype.RTrim = function() { return this.replace(/(\s*$)/g, ""); }
String.prototype.Filter = function() {
    var re = /select|update|delete|exec|count|\'|\||;|"|=|\;|>|<|%/g;
    return this.replace(re, "");
}

String.prototype.endWith = function(s) {
    var p = this.lastIndexOf(s);
    if (p + s.length == this.length) {
        return true;
    } else
        return false;
}
//format number "#" int,"#.00" float,"#.00#","#.0%":present
Number.prototype.format = function(f) {
    var n = this;

    if (f == null) f = "#.00";
    var isPercent = false;
    if (f.endWith("%")) {
        isPercent = true;
        n = n * 100;
        f = f.substring(0, f.length - 1);
    }
    var v;
    if (f == "#") {
        v = String(Math.round(n));
    } else {
        var c = 0;
        if (f.endWith("#")) {
            c = f.length - 3;
            v = "" + n;
        } else {
            c = f.length - 2;
            var p = Math.pow(10, c);
            var t = p * n;
            t = Math.round(t);
            v = String(t / p);
        }
        if (c > 0) {
            if (v.indexOf(".") === -1) {
                v = v + ".0";
            }
            var p = v.indexOf(".") + 1;
            if (v.length - p < c) {
                var l = c - (v.length - p);
                for (var i = 0; i < l; i++) {
                    v = v + "0";
                }
            }
        }
    }
    if (isPercent === true) {
        v = v + "%";
    }
    return v;
}

//delete the same itmes
Array.prototype.unique = function() {
    var temp = new Array();
    for (var i = 0; i < this.length; i++) {
        if (this[i] == undefined) continue;
        var t = false;
        for (var j = 0; j < temp.length; j++) {
            if (this[i] == temp[j])
            { t = true; break; }
        }
        if (!t)
            temp.push(this[i]);
    }
    return temp;
}


//Json
function json2str(o) {
    var r = [];
    if (typeof o == "string" || o == null) {
        return "'" + o + "'";
    }
    if (typeof o == "object") {
        if (!o.sort) {
            r[0] = "{"
            for (var i in o) {
                r[r.length] = i;
                r[r.length] = ":";
                r[r.length] = json2str(o[i]);
                r[r.length] = ",";
            }
            r[r.length - 1] = "}"
        } else {
            r[0] = "["
            for (var i = 0; i < o.length; i++) {
                r[r.length] = json2str(o[i]);
                r[r.length] = ",";
            }
            r[r.length - 1] = "]"
        }
        return r.join("");
    }
    return o.toString();
}

//string json object
function str2json(str) {
    return eval("(" + str + ")");
}

function switchKey() {
    if (window.event.keyCode == 13) window.event.keyCode = 9
}


/*
* SmartGrid Extent Method
*/
function GetSelectedRows(gridID) {
    aryItems = yy_GetDateForItems(gridID);

    if (aryItems == null) return 0;
    if (aryItems && aryItems.length == 1) {
        aryItem = aryItems[0].split(itemSeparator);
        var count = 0;
        for (var j = 0; j < aryItem.length; j++) {
            if (yy_GetObject(aryItem[j]) && yy_GetObject(aryItem[j]).checked) {
                count++;
            }
        }
        return count;
    }
    return 0;
}
function IsSelectedOne(gridID) {
    return GetSelectedRows(gridID) == 1;
}
function IsNotSelected(gridID) {
    return GetSelectedRows(gridID) == 0;
}
/*
* SmartGrid Extent Method End
*/

//only num
function clearNoNum(obj) {
    obj.value = obj.value.replace(/[^\d]/g, "");
}
//only num and letter
function clearNoNumLet(obj) {
    obj.value = obj.value.replace(/[^\d\w]/g, "");
}

function doPrint(title, type) {
    bdhtml = window.document.body.innerHTML;
    sprnstr = "<!--startprint-->";
    eprnstr = "<!--endprint-->";
    prnhtml = bdhtml.substr(bdhtml.indexOf(sprnstr) + 17);
    prnhtml = prnhtml.substring(0, prnhtml.indexOf(eprnstr));

    prnhtml = prnhtml.replace(/<!--ignorestart-->(.*)<!--ignoreend-->/g, "");

    //prnhtml = RemoveAH(prnhtml);
    ifmPrint.document.title = title;
    ifmPrint.document.body.innerHTML = prnhtml;
    ifmPrint.focus();
    ifmPrint.todo();
}

//delete Tag
function RemoveHTML(strText) {
    var regEx = /<[^>]*>/g;
    return strText.replace(regEx, "");
}
//delete A and Text
function RemoveA(strText) {
    var regEx = /<(A|a)[^>]*>[^>]*<[^>](A|a)>/g;
    return strText.replace(regEx, "");
}
//delete A
function RemoveAH(strText) {
    var regEx = /(<(A|a)[^>]*>)|(<[^>](A|a)>)/g;
    return strText.replace(regEx, "");
}

function openwindow(url, name, iWidth, iHeight) {
    var url; var name; var iWidth; var iHeight;
    var iTop = (window.screen.availHeight - 30 - iHeight) / 2;
    var iLeft = (window.screen.availWidth - 10 - iWidth) / 2;
    window.open(url, name, 'height=' + iHeight + ',innerHeight=' + iHeight + ',width=' + iWidth + ',innerWidth=' + iWidth + ',top=' + iTop + ',left=' + iLeft + ',toolbar=no,menubar=yes,scrollbars=yes,resizable=yes,location=no,status=no');
}

//set form readonly intput
function setReadOnly(frm) {
    $(frm).find('input[readOnly!=""]').css('border-color', '#fff');
}
/**
* goto top
* @param acceleration 
* @param time
**/
function goTop(acceleration, time) {
    acceleration = acceleration || 0.1;
    time = time || 16;

    var x1 = 0;
    var y1 = 0;
    var x2 = 0;
    var y2 = 0;
    var x3 = 0;
    var y3 = 0;

    if (document.documentElement) {
        x1 = document.documentElement.scrollLeft || 0;
        y1 = document.documentElement.scrollTop || 0;
    }
    if (document.body) {
        x2 = document.body.scrollLeft || 0;
        y2 = document.body.scrollTop || 0;
    }
    var x3 = window.scrollX || 0;
    var y3 = window.scrollY || 0;

    var x = Math.max(x1, Math.max(x2, x3));
    var y = Math.max(y1, Math.max(y2, y3));

    var speed = 1 + acceleration;
    window.scrollTo(Math.floor(x / speed), Math.floor(y / speed));

    if (x > 0 || y > 0) {
        var invokeFunction = "goTop(" + acceleration + ", " + time + ")";
        window.setTimeout(invokeFunction, time);
    }
}

//get OS 
function detectOS() {
    var sUserAgent = navigator.userAgent;
    var isWin = (navigator.platform == "Win32") || (navigator.platform == "Windows");
    var isMac = (navigator.platform == "Mac68K") || (navigator.platform == "MacPPC") || (navigator.platform == "Macintosh");
    if (isMac) return "Mac";
    var isUnix = (navigator.platform == "X11") && !isWin && !isMac;
    if (isUnix) return "Unix";
    var isLinux = (String(navigator.platform).indexOf("Linux") > -1);
    if (isLinux) return "Linux";
    if (isWin) {
        var isWin2K = sUserAgent.indexOf("Windows NT 5.0") > -1 || sUserAgent.indexOf("Windows 2000") > -1;
        if (isWin2K) return "Win2000";
        var isWinXP = sUserAgent.indexOf("Windows NT 5.1") > -1 || sUserAgent.indexOf("Windows XP") > -1;
        if (isWinXP) return "WinXP";
        var isWin2003 = sUserAgent.indexOf("Windows NT 5.2") > -1 || sUserAgent.indexOf("Windows 2003") > -1;
        if (isWin2003) return "Win2003";
    }
    return "None";
}
function loadCss(file) {
    var cssTag = document.getElementById('loadCss');
    var head = document.getElementsByTagName('head').item(0);
    if (cssTag) head.removeChild(cssTag);
    css = document.createElement('link');
    css.href = file;
    css.rel = 'stylesheet';
    css.type = 'text/css';
    css.id = 'loadCss';
    head.appendChild(css);
}
