//leedialog.js
// Lee dialog 1.0 http://www.xij.cn/blog/?p=68

var dialogFirst = true;
var _height = 0;
function dialog(title, content, width, height, cssName) {

    if (dialogFirst == true) {
        var temp_float = new String;
        temp_float = "<div id=\"floatBoxBg\" style=\"height:" + jQuery(document).height() + "px;filter:alpha(opacity=0);opacity:0;\"></div>";
        temp_float += "<div id=\"floatBox\" class=\"floatBox\">";
        temp_float += "<div class=\"title\"><h4></h4><span onclick='Dialog_Close()'><img src='http://content1.ijie.cn/zh-cn/image/tools/checklist/modal_btn_close.png' /></span></div>";
        temp_float += "<div class=\"content\"></div>";
        temp_float += "</div>";
        jQuery("body").append(temp_float);
        dialogFirst = false;
        _height = height;
        jQuery("#floatBox").jqDrag(".title");
    }

    //    jQuery("#floatBox .title span").click(function() {
    //        alert("Test");
    //        jQuery("#floatBoxBg").animate({ opacity: "0" }, "normal", function() { jQuery(this).hide(); });
    //        jQuery("#floatBox").animate({ top: (jQuery(document).scrollTop() - (height == "auto" ? 300 : parseInt(height))) + "px" }, "normal", function() { jQuery(this).hide(); });
    //    });

    jQuery("#floatBox .title h4").html(title);
    contentType = content.substring(0, content.indexOf(":"));
    content = content.substring(content.indexOf(":") + 1, content.length);
    switch (contentType) {
        case "url":
            var content_array = content.split("?");
            jQuery("#floatBox .content").ajaxStart(function() {
                jQuery(this).html("loading...");
            });
            jQuery.ajax({
                type: content_array[0],
                url: content_array[1],
                data: content_array[2],
                error: function() {
                    jQuery("#floatBox .content").html("error...");
                },
                success: function(html) {
                    jQuery("#floatBox .content").html(html);
                }
            });
            break;
        case "text":
            jQuery("#floatBox .content").html(content);
            break;
        case "id":
            jQuery("#floatBox .content").html(jQuery("#" + content + "").html());
            break;
        case "iframe":
            jQuery("#floatBox .content").html("<iframe src=\"" + content + "\" width=\"100%\" height=\"" + (parseInt(height) - 30) + "px" + "\" scrolling=\"auto\" frameborder=\"0\" marginheight=\"0\" marginwidth=\"0\"></iframe>");
    }

    jQuery("#floatBoxBg").show();
    jQuery("#floatBoxBg").animate({ opacity: "0.5" }, 0);
    jQuery("#floatBox").attr("class", "floatBox " + cssName);
    jQuery("#floatBox").css({ display: "block", left: ((jQuery(document).width()) / 2 - (parseInt(width) / 2)) + "px", width: width, height: height });
    var floatBoxheight = parseInt(document.getElementById("floatBox").offsetHeight, 10);
    var topset = ($(window).height()) / 2 - (parseInt(floatBoxheight) / 2) + $(document).scrollTop();
    if (topset < 0) topset = 0;
    jQuery("#floatBox").css({ top: topset + "px" });
    $(window).scroll(function() {
        jQuery("#floatBox").animate({ top: (($(window).height()) / 2 - (parseInt(floatBoxheight) / 2) + $(document).scrollTop()) + "px" }, 0);
    });
}


function Dialog_Close() {
    jQuery("#floatBoxBg").animate({ opacity: "0" }, 0, function() { jQuery(this).hide(); });
    jQuery("#floatBox").animate({ opacity: "1" }, 0, function() { jQuery(this).hide(); });
}
(function($) {
    $.fn.jqDrag = function(h) { return i(this, h, 'd'); };
    $.fn.jqResize = function(h) { return i(this, h, 'r'); };
    $.jqDnR = { dnr: {}, e: 0,
        drag: function(v) {
            if (M.k == 'd') E.css({ left: M.X + v.pageX - M.pX, top: M.Y + v.pageY - M.pY });
            else E.css({ width: Math.max(v.pageX - M.pX + M.W, 0), height: Math.max(v.pageY - M.pY + M.H, 0) });
            return false;
        },
        stop: function() { E.css('opacity', M.o); $().unbind('mousemove', J.drag).unbind('mouseup', J.stop); }
    };
    var J = $.jqDnR, M = J.dnr, E = J.e,
i = function(e, h, k) {
    return e.each(function() {
        h = (h) ? $(h, e) : e;
        h.bind('mousedown', { e: e, k: k }, function(v) {
            var d = v.data, p = {}; E = d.e;
            // attempt utilization of dimensions plugin to fix IE issues
            if (E.css('position') != 'relative') { try { E.position(p); } catch (e) { } }
            M = { X: p.left || f('left') || 0, Y: p.top || f('top') || 0, W: f('width') || E[0].scrollWidth || 0, H: f('height') || E[0].scrollHeight || 0, pX: v.pageX, pY: v.pageY, k: d.k, o: E.css('opacity') };
            E.css({ opacity: 1 }); $().mousemove($.jqDnR.drag).mouseup($.jqDnR.stop);
            return false;
        });
    });
},
f = function(k) { return parseInt(E.css(k)) || false; };
})(jQuery);

//login.js
(function(jQuery) {
    jQuery.extend({
        TK: {
            getCookie: function(name) {
                var reg = new RegExp(name + '=([\\w-&=%]+)(;|$)', 'ig');
                var cookie = reg.exec(document.cookie);

                if (cookie != null) {
                    return {
                        toString: function() {
                            return cookie[1];
                        },

                        getValue: function(name) {
                            var reg = new RegExp(name + '=([\\w-%]+)', 'ig');
                            var value = reg.exec(cookie[1]);

                            return (value != null) ? value[1] : value;
                        }
                    };
                }

                return {
                    toString: function() {
                        return '';
                    },

                    getValue: function(name) {
                        return null;
                    }
                };
            },

            setCookie: function(name, value, expires, path, domain, secure) {
                document.cookie = name + "=" + escape(value) +
				((expires) ? "; expires = " + expires.toGMTString() : "") +
				((path) ? "; path=" + path : "") +
				((domain) ? "; domain = " + domain : "") +
				((secure) ? "; secure" : "");
            },

            fixCookieDateForMac: function(date) {
                var base = new Date(0);
                var skew = base.getTime(); // dawn of (Unix) time - should be 0

                if (skew > 0) {  // Except on the Mac
                    date.setTime(date.getTime() - skew);
                }
            },

            validationLogin: function() {
                var userId = jQuery.TK.getCookie('TMPAUTHTIX').getValue('userId');

                if (userId != null) {
                    jQuery.getJSON('http://global.ijie.com/join/LoginVerification.ashx?jsoncallback=?', { 'userId': userId }, function(data) {
                        jQuery('div.headerlinks.LoginUserName').remove();
                        if (data != null && data.userName != null) {
                            jQuery('div.headerlinks').prepend('<span id="WidgetsHeader_ctl01_labLoginUserName" class="LoginUserName">' + data.userName + '</span>');
                            jQuery("#WidgetsHeader_ctl01_HyperLink3").attr("title", "登出");
                            jQuery("#WidgetsHeader_ctl01_HyperLink3").attr("href", "javascript:Open_LogoutPage('http://global.ijie.com/join/logout.aspx');");
                            jQuery("#WidgetsHeader_ctl01_HyperLink3").removeAttr("onclick");
                            jQuery("#WidgetsHeader_ctl01_HyperLink3").html("登出");

                            jQuery("#WidgetsHeader_ctl01_HyperLink4").attr("title", "我的账户");
                            jQuery("#WidgetsHeader_ctl01_HyperLink4").attr("href", "http://global.ijie.com/join/memberprofile.aspx");
                            jQuery("#WidgetsHeader_ctl01_HyperLink4").removeAttr("onclick");
                            jQuery("#WidgetsHeader_ctl01_HyperLink4").html("我的账户");

                        }
                    });
                }
            },

            menuNav: {
                heightlightItem: function(itemID) {
                    var anchors = jQuery('div#topnav a');
                    for (var i = 0; i < anchors.length; i++) {
                        jQuery(anchors[i]).toggleClass('selected', (i == itemID - 1));
                    }
                }
            }
        }
    });

    jQuery(document).ready(function() {
        var host = jQuery.trim(window.location.host);
        var subdomain = (host == '' ? '' : host.split('.')[0]).toLowerCase();

        if (subdomain == 'forum' || subdomain == 'blog') {
            jQuery.TK.validationLogin();
            jQuery.TK.menuNav.heightlightItem(7);
        }
        else if (subdomain != 'www') {
            jQuery.TK.menuNav.heightlightItem(2);
        }
    });
})(jQuery);


//app_functions.js




// run on pageload
dom_addLoadEvent(FixExternalLinks);
dom_addLoadEvent(correctPNG);



// corrects PNG images to get PNG transparency to work in IE
function correctPNG() {
    var arVersion = navigator.appVersion.split("MSIE")
    var version = parseFloat(arVersion[1])

    if ((version >= 5.5 && version < 7) && (document.body.filters)) {
        for (var i = 0; i < document.images.length; i++) {
            var img = document.images[i]
            var imgName = img.src.toUpperCase()
            if (imgName.substring(imgName.length - 3, imgName.length) == "PNG") {
                var imgID = (img.id) ? "id='" + img.id + "' " : ""
                var imgClass = (img.className) ? "class='" + img.className + "' " : ""
                var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
                var imgStyle = "display:inline-block;" + img.style.cssText
                if (img.align == "left") imgStyle = "float:left;" + imgStyle
                if (img.align == "right") imgStyle = "float:right;" + imgStyle
                if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
                var strNewHTML = "<span " + imgID + imgClass + imgTitle
             + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
             + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
             + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
                img.outerHTML = strNewHTML
                i = i - 1
            }
        }
    }
}



// swaps an image with a specific id to a new image url
function swap(id, url) {
    var oImg = document.getElementById(id);
    oImg.src = url;
}



// toggle for left menu options
function toggleMainNav(oThisMenuLink) {
    var oThisMenuLinksArrowImageArray = oThisMenuLink.parentNode.getElementsByTagName("img");
    var oThisMenuLinksArrowImage = oThisMenuLinksArrowImageArray[0];
    var oThisParentContainer = oThisMenuLink.parentNode.parentNode;
    var arrNavDivs = dom_getElementsByClassName(document, 'div', 'mainnav_mainlevel');

    // close all other submenus
    /*
    for (var i=0; i<arrNavDivs.length; i++)
    {
    if (arrNavDivs[i] !== oThisParentContainer)
    {
    dom_removeClassName(arrNavDivs[i], 'onstate');
    }
    }	
    */

    // open or close (toggle) proper submenu (and title text for arrow image)
    if (!dom_hasClassName(oThisParentContainer, 'onstate')) {
        dom_addClassName(oThisParentContainer, 'onstate');
        if (typeof (oThisMenuLinksArrowImage) != "undefined") {
            oThisMenuLinksArrowImage.setAttribute('alt', 'click to hide');
            oThisMenuLinksArrowImage.setAttribute('title', 'click to hide');
        }
    }
    else {
        dom_removeClassName(oThisParentContainer, 'onstate');
        if (typeof (oThisMenuLinksArrowImage) != "undefined") {
            oThisMenuLinksArrowImage.setAttribute('alt', 'click to expand');
            oThisMenuLinksArrowImage.setAttribute('title', 'click to expand');
        }
    }

}



// toggle for tab content boxes
function toggleTabContent(oThisMenuLink, iTabContentId) {
    var oThisContentDiv = document.getElementById('tabcontent_' + iTabContentId);
    var arrMenuLinks = dom_getElementsByClassName(document, 'a', 'tabbedboxmenulink');
    var arrContentDivs = dom_getElementsByClassName(document, 'div', 'tabbedboxcontent');

    // close all other content boxes
    for (var i = 0; i < arrContentDivs.length; i++) {
        if (arrContentDivs[i] !== oThisContentDiv) {
            dom_removeClassName(arrContentDivs[i], 'onstate');
        }
    }

    // open or close (toggle) proper content box
    if (!dom_hasClassName(oThisContentDiv, 'onstate')) {
        dom_addClassName(oThisContentDiv, 'onstate');
    }

    // close all other tab links
    for (var i = 0; i < arrMenuLinks.length; i++) {
        if (arrMenuLinks[i] !== oThisMenuLink) {
            dom_removeClassName(arrMenuLinks[i], 'onstate');
        }
    }

    // open or close (toggle) proper tab link
    if (!dom_hasClassName(oThisMenuLink, 'onstate')) {
        dom_addClassName(oThisMenuLink, 'onstate');
    }

    return false;
}

function CreateBookmarkLink() {
    title = document.title; url = location.href;
    if (window.sidebar) { // Mozilla Firefox Bookmark
        window.sidebar.addPanel(title, url, "");
    } else if (window.external) { // IE Favorite
        window.external.AddFavorite(url, title);
    }
    else if (window.opera && window.print) { // Opera Hotlist
        return true;
    }
}

function open_popup(url, w, h, resize, scroll, wname) {
    /* place this in onclick or href: "javascript:open_popup('[url]','[width of window]','[height of window]','[resize option]','[scroll opiton]','[windowname]');" */
    wname = (wname == null) ? "popwin" : wname.replace(new RegExp(/ /g), "");
    scroll = ((scroll == null) || (scroll == '') || (scroll == 1) || (scroll == '1')) ? 'yes' : 'no';
    resize = ((resize == null) || (resize == '') || (resize == 1) || (resize == '1')) ? 'yes' : 'no';
    var properties = "toolbar=0,scrollbars=" + scroll + ",location=0,statusbar=1,menubar=0,resizable=" + resize;
    properties += ",width=" + w + ",height=" + h;
    child = window.open(url, wname, properties);
    child.focus();
}























// ### General Utility & DOM Handling Functions Below This Line



// ### gets an array of objects that match the input start element, tag name, and class name
// Ways of calling the function are:
// To get all a elements in the document with a 搃nfo-links?class. 
// getElementsByClassName(document, "a", "info-links"); 
// To get all div elements within the element named 揷ontainer? with a 揷ol?and a 搇eft?class. 
// getElementsByClassName(document.getElementById("container"), "div", ["col", "left"]); 
function dom_getElementsByClassName(oElm, strTagName, oClassNames) {
    var arrElements = (strTagName == "*" && document.all) ? document.all :
    oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    var arrRegExpClassNames = new Array();
    if (typeof oClassNames == "object") {
        for (var i = 0; i < oClassNames.length; i++) {
            arrRegExpClassNames.push(new RegExp("(^|\\s)" +
            oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)"));
        }
    }
    else {
        arrRegExpClassNames.push(new RegExp("(^|\\s)" +
        oClassNames.replace(/\-/g, "\\-") + "(\\s|$)"));
    }
    var oElement;
    var bMatchesAll;
    for (var j = 0; j < arrElements.length; j++) {
        oElement = arrElements[j];
        bMatchesAll = true;
        for (var k = 0; k < arrRegExpClassNames.length; k++) {
            if (!arrRegExpClassNames[k].test(oElement.className)) {
                bMatchesAll = false;
                break;
            }
        }
        if (bMatchesAll) {
            arrReturnElements.push(oElement);
        }
    }
    return (arrReturnElements)
}



function dom_addClassName(oElm, strClassName) {
    var strCurrentClass = oElm.className;
    if (!new RegExp(strClassName, "i").test(strCurrentClass)) {
        oElm.className = strCurrentClass + ((strCurrentClass.length > 0) ? " " : "") + strClassName;
    }
}



function dom_removeClassName(oElm, strClassName) {
    var oClassToRemove = new RegExp((strClassName + "\s?"), "i");
    oElm.className = oElm.className.replace(oClassToRemove, "").replace(/^\s?|\s?$/g, "");
}



function dom_hasClassName(oElm, strClassName) {
    return oElm.className.match(new RegExp('(\\s|^)' + strClassName + '(\\s|$)'));
}



// ### adds a function to run at onLoad
function dom_addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    }
    else {
        window.onload = function() {
            oldonload();
            func();
        }
    }
}





//externallinks.js
//////




function FixExternalLinks() {
    var objLinks = document.getElementsByTagName('a');

    for (var iCounter = 0; iCounter < objLinks.length; iCounter++) {
        if (objLinks[iCounter].getAttribute('href') && objLinks[iCounter].getAttribute('rel') == 'external') {
            objLinks[iCounter].setAttribute('target', '_blank');
        }
        else if (objLinks[iCounter].getAttribute('href') && objLinks[iCounter].getAttribute('rel') == 'top') {
            objLinks[iCounter].setAttribute('target', '_top');
        }
    }
}




//////

// header js
function addPageToBookmark(obj, url, title) {
    // add the event details.
    var e = window.event || arguments.callee.caller.arguments[0];

    // determine the browser type.
    var browserType = {
        IE: /MSIE/.test(window.navigator.userAgent) && !window.opera,
        FF: /Firefox/.test(window.navigator.userAgent),
        OP: !!window.opera
    };

    obj.onmousedown = null;

    // add bookmark for IE.
    if (browserType.IE) {
        obj.attachEvent("onmouseup", function() {
            try {
                window.external.AddFavorite(url, title);
                window.event.returnValue = false;
            } catch (exp) {
            }
        });
    }
    else {
        // add bookmark for FF.
        if (browserType.FF) {
            obj.setAttribute("rel", "sidebar"),
			obj.title = title,
			obj.href = url;
        }
    }
};

function Open_LogoutPage(url) {
    open_popup(url, 370, 300, 1, 1, '');
    setTimeout("ReloadPage()", 1000);
}
function ReloadPage() {
    //location.reload(true);
    window.location.href = window.location.href;
}

// show overlay to gather the feedback details.
function showFeedbackOverlay() {
    // display the overlay.
    var overlayTitle = "";
    var link = "http://www.ijie.com/Sites/TheKnotChina/Feedback.aspx";
    dialog(overlayTitle, 'iframe:' + link, '600px', '385px', 'iframe');
}
function loginOrSignup(url) {
    var targetUrl = jQuery.trim(window.location.href);
    if (targetUrl.indexOf('target=') > -1) {
        targetUrl = unescape(targetUrl);
        targetUrl = targetUrl.substring(targetUrl.indexOf('target=') + 7);
    }
    url = jQuery.trim(url);
    if (url != '') {
        url += '?target=' + escape(targetUrl);
        window.location.href = url;
    }
}

// multiligual
function changeLanguage(culture) {
    location.href = "http://www.ijie.com/Sites/TheKnotChina/ChangeLanguage.ashx?lang=" + culture + "&returnUrl=" + location.href;
}
function getCookie(name) {
    var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
    if (arr != null) return unescape(arr[2]); return null;
}
function setLanguageSelection() {
    var lang_cookie = getCookie("lang");
    if (lang_cookie) {
        document.getElementById("ddlLanguage").value = lang_cookie;
    }
}

