var addType =null;
var addId = null;

/* help people that don't have a wide monitor */
$(document).ready(resizeDisplay);
/* start the menus */
$(document).ready(setMenu);
/* switch PNG for IE5 and 6 */
$(document).ready(correctPNG);
/* init the top nav */
$(document).ready(initTopMenu);
/* init the buttons */
$(document).ready(initButtons);
/* bind the login box */
$(document).ready(bindLoginPasswordTextbox);
/* adjust the size of the text in images in places */
$(document).ready(setSizes);
/* set teh size of the images in fly out nav*/
$(document).ready(resizeImagesInMenu);

function resizeDisplay() {
    if ($(window).width() < 1200) {
        // change to 1000 width
        $(".breadcrumbs_inside").css("padding-left", "10px");
        $(".submenu_left").css("padding-left", "10px");
        $(".footer_menu").css("padding-left", "10px");
        $("#mykarastan_main_bot").css("padding-left", "10px");
        $(".topArea").css("padding-left", "10px");

        $(".copyright").css("padding-right", "10px");

        $(".logo_pos").css("left", "10px");
        $(".menu_text").css("left", "260px");
        $(".top_right_srch").css("right", "0px");
        $(".top_right_nav").css("right", "0px");

        $("#mainbody").css("width", "1000px");
        $(".breadcrumbs").css("width", "1000px");
        $(".topdiv").css("width", "1000px").css("background-position", "-150px 78px");
        $(".main_body_inside").css("width", "1000px");
        $(".divImg").css("width", "1130px").css("margin-left","-150px");
        $(".bottom_container").css("width", "1000px");
        $(".main_body").css("width", "1000px").css("min-width", "1000px");

        $(".sub_menu_designcreate_level1").css("width", "1000px").css("padding-left", "10px");

        $("#homeFlashWrapper").css("margin-left", "-140px").css("width", "1140px").css("overflow","hidden");
        
    }
}

/* set which menu should be highlighted */
function setMenu() {
    $(".subMenuShowHide").click(showSubMenu);
    $(".subMenuShowHide1").click(showSubMenu1);

    if (typeof contentIdToHighlight != "undefined") {
        var g = $("#menuItem-" + contentIdToHighlight);
        if (g != null) {
            g.css("color", "#663300").show();

            g.parents("dd").map(function() {
                //$(this).css("color", "#663300").show();
                $(this).css("color", "#663300");
                $("#" + this.id.replace("subleftmenu", "leftmenu")).css("color", "#663300");
                $("#" + this.id.replace("subleftmenu", "leftmenu1")).click();
            });

            g.parents("ul[id]").map(function() {
                $(this).show();
                $("#" + this.id.replace("submenuItem", "menuItem")).css("color", "#663300");
            });
        }
    }
}

function showSubMenu1() {
    $(this).parent().children(".subMenuShowHide").click();
}

/* show a menu on the left nav*/
function showSubMenu() {
    $(this).html(" - ").unbind('click',showSubMenu).click(hideSubMenu).parent().parent().children("dd").toggle();
}

/* hide a menu on the left nav*/
function hideSubMenu() {
    $(this).html(" + ").unbind('click', hideSubMenu).click(showSubMenu).parent().parent().children("dd").toggle();
}

jQuery.fn.supersleight = function(settings) {
    settings = jQuery.extend({
        imgs: true,
        backgrounds: true,
        shim: '/karastanassets/images/spacer.gif',
        apply_positioning: true
    }, settings);

    return this.each(function() {
        if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 7 && parseInt(jQuery.browser.version, 10) > 4) {
            jQuery(this).find('*').andSelf().each(function(i, obj) {
                var self = jQuery(obj);
                // background pngs
                if (settings.backgrounds && self.css('background-image').match(/\.png/i) !== null) {
                    var bg = self.css('background-image');
                    var src = bg.substring(5, bg.length - 2);
                    var mode = (self.css('background-repeat') == 'no-repeat' ? 'crop' : 'scale');
                    var styles = {
                        'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + mode + "')",
                        'background-image': 'url(' + settings.shim + ')'
                    };
                    self.css(styles);
                };
                // image elements
                if (settings.imgs && self.is('img[src$=png]')) {
                    var styles = {
                        'width': self.width() + 'px',
                        'height': self.height() + 'px',
                        'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + self.attr('src') + "', sizingMethod='scale')"
                    };
                    self.css(styles).attr('src', settings.shim);
                };
                // apply position to 'active' elements
                if (settings.apply_positioning && self.is('a, input') && (self.css('position') === '' || self.css('position') == 'static')) {
                    self.css('position', 'relative');
                };
            });
        };
    });
};


/* correctly handle PNG transparency in Win IE 5.5 & 6.*/
function correctPNG() {
    $('body').supersleight();
}

/* init the top hand nav */
function initTopMenu() {
    $(".dd").hover(showMenu, hideMenu);
}

/* show the top hand nav */
function showMenu(i) {
    $(this).css("border-color", "#cccccc");
    $(this).children(".dd_content").stop(true, true).slideDown("slow");
    $(this).children(".dd_title").css("color", "#663300");
}

/* hide a top hand nav */
function hideMenu(i) {
    $(this).css("border-color", "#ffffff");
    $(this).children(".dd_content").stop(true, true).slideUp("slow");
    $(this).children(".dd_title").css("color", "#666666");
}

/* handle the mouse over on buttons*/
function initButtons() {
    $(".btn").hover(
        function() {
            $(this).toggleClass("btnOver");
        },
        function() {
            $(this).toggleClass("btnOver");
        }
        );
}

/* bind the enter box in the login*/
function bindLoginPasswordTextbox() {
    $("#pass").keydown(function(event) { return submitEnter('btnLogin', event.keyCode); });
}

/* set teh width andheight on items so columns and rows match*/
function setSizes() {
    $(".topImg").load(setTopTextWidth);
    $(".btmImg img").load(setBottomTextWidth);

    var maxHeight = 0;
    $(".btmTxt").each(function(i) {
        if ($(this).height() > maxHeight) {
            maxHeight = $(this).height();
        }
    });
    $(".btmTxt").height(maxHeight);

    maxHeight = 0;
    $(".btmTxt1").each(function(i) {
        if ($(this).height() > maxHeight) {
            maxHeight = $(this).height();
        }
    });
    $(".btmTxt1").height(maxHeight);

    $(".btmImg").each(function(i) {
        if ($(this).height() > btnImageMaxHeight) {
            btnImageMaxHeight = $(this).height();
        }
    });
    $(".btmImg").height(btnImageMaxHeight);

    setTopTextWidth();
}

/*Set teh width on the top text where an image is next to it*/
function setTopTextWidth() {
    if ($(".topImg").width() > 100) {
        $(".topText").width((750 - $(".topImg").width()));
    }
}

/* set the images in bottom navigation lists to be same height*/
var btnImageMaxHeight = 0;
function setBottomTextWidth() {
    if ($(this).height() > btnImageMaxHeight) {
        btnImageMaxHeight = $(this).height();
    }
    $(".btmImg").height(btnImageMaxHeight);
}


/* resize all the images in a fly out navs*/
function resizeImagesInMenu() {
    $(".dc_table_img > img").load(resizeImagesInMenu1);
    resizeImagesInMenu1();
}

/* resize all the images in a fly out navs*/
function resizeImagesInMenu1() {
    $(".dc_table").each(function(x) {
        var maxHeight = 0;
        $(this).children(".dc_table_col").children(".dc_table_img").each(function(y) {
            var h = $(this).children("img").attr("height");
            if (h > 0 && h > maxHeight) {
                maxHeight = h;
            }
        });
        if (maxHeight > 0) {
            $(this).children(".dc_table_col").children(".dc_table_img").height(maxHeight);
        }
    });
}

/* set the breadcrumb text based on a selected menu*/
function setBreadcrumb(id) {
    $("#bc").html($("#menuItem-" + id).html());
}

/* show a flyout menu*/
var curShowingSubMenu = -1;
function showdcmenu1(boxid, wide) {
    $("#dcmenu_sub_" + curShowingSubMenu).width(340).hide();
    $("#dcmenu_title_" + curShowingSubMenu).css("color", "#999999").width(340 - 14);
    if (curShowingSubMenu != boxid) {
        curShowingSubMenu = boxid;
        $("#dcmenu_sub_" + boxid).width(wide).show();
        $("#dcmenu_title_" + boxid).css("color", "#663300").width(wide - 14);

        var maxHeight = 0;
        $(".dc_table_head" + boxid).each(function(x) {
            if ($(this).height() > maxHeight) {
                maxHeight = $(this).height();
            }
        });
        $(".dc_table_head" + boxid).height(maxHeight);

        maxHeight = 0;
        $(".dc_table_txt" + boxid).each(function(x) {
            if ($(this).height() > maxHeight) {
                maxHeight = $(this).height();
            }
        });
        $(".dc_table_txt" + boxid).height(maxHeight);
    }
    else {
        curShowingSubMenu = -1;
    }
}



/* set which states are viewed in dropdowns based on country*/
function setCountry() {
    $("#ctl00_contentPlaceHolderMain_ddUSstates, #ctl00_contentPlaceHolderMain_ddCAstates").hide();
    var c = $("#ctl00_contentPlaceHolderMain_ddCountry").val();
    $("#ctl00_contentPlaceHolderMain_dd" + c + "states").show()
}

/* clear what is entered in a textbox when focus*/
function clearTextBox(id, d) {
    if ($("#" + id).val() == d) {
        $("#" + id).val("");
    };
}

/* click a button if the enter key is pressed in a textbox*/
function submitEnter(id, key) {
    if ((key && key == 13)) 
    {
        $("#" + id).click();
        return false;
    };
    return true;
}

/* launch room scene*/
function launchRugPlanner() {
    tb_show("", "http://karastan.icovia.com/icovia.aspx?TB_iframe=true&height=600&width=800&modal=true", null, "", true);
}


/* launch room scene*/
function launchRoomSceneViewer(id, title) {
    tb_show("", "/RoomSceneListing.aspx?id=" + id + "&title=" + title + "&TB_iframe=true&height=720&width=700&modal=true", null, "", true);
}

/* launch carpet estimator*/
function launchCarpetEstimator(id, price) {
    tb_show("", "/CarpetEstimator.aspx?id=" + id + "&price=" + price + "&TB_iframe=true&height=600&width=700&modal=true", null, "", true);
}

/* launch carpet opup*/
function showCarpetPopup(id, lookupId, type, startIndex, source) {
    //var page = "/CarpetPopup.aspx?t=" + Math.round(Math.random() * 10000) + "&id=" + id + "&lookupId=" + lookupId + "&type=" + type + "&startIndex=" + startIndex + "&source=" + source + "&TB_iframe=true&height=325&width=440&modal=true";
    //var page = "/CarpetPopup1.aspx?t=" + Math.round(Math.random() * 10000) + "&id=" + id + "&lookupId=" + lookupId + "&type=" + type + "&startIndex=" + startIndex + "&source=" + source + "&height=335&width=450&modal=true";
    var page = "/CarpetPopup1.aspx?t=" + Math.round(Math.random() * 10000) + "&id=" + id + "&lookupId=" + lookupId + "&type=" + type + "&startIndex=" + startIndex + "&source=" + source + "&height=700&width=700&modal=true";
    tb_show("", page, null, "", true);
}

/* launch rug opup*/
function showRugPopup(id, lookupId, type, startIndex, source) {
    //var page = "/CarpetPopup.aspx?t=" + Math.round(Math.random() * 10000) + "&id=" + id + "&lookupId=" + lookupId + "&type=" + type + "&startIndex=" + startIndex + "&source=" + source + "&TB_iframe=true&height=325&width=440&modal=true";
    //var page = "/RugPopup.aspx?t=" + Math.round(Math.random() * 10000) + "&id=" + id + "&lookupId=" + lookupId + "&type=" + type + "&startIndex=" + startIndex + "&source=" + source + "&height=420&width=425&modal=true";
    var page = "/RugPopup.aspx?t=" + Math.round(Math.random() * 10000) + "&id=" + id + "&lookupId=" + lookupId + "&type=" + type + "&startIndex=" + startIndex + "&source=" + source + "&height=700&width=700&modal=true";
    
    tb_show("", page, null, "", true);
}
function moreInfo(url) {
    tb_remove();
    window.setTimeout("window.location = '" + url + "'",100);
}

/* launch dealer locator for directions*/
function showDealerLocatorDirectionsPopup(from, to) {
    tb_show("", "DealerLocatorDirections.aspx?fromAddress=" + from + "&toAddress=" + to + "&TB_iframe=true&height=600&width=800&modal=true", null, "", true);
}

function showDealerLocatorDirectionsPopup1(id) {
    var from = $("#ctl00_contentPlaceHolderMain_textBoxPostalCode").val();
    var to = $("#address1-" + id).html() + "," + $("#address2-" + id).html();
    tb_show("", "DealerLocatorDirections.aspx?fromAddress=" + escape(from) + "&toAddress=" + escape(to) + "&TB_iframe=true&height=500&width=700&modal=true", null, "", true);
}

/* launch click to connect*/
function showClickToConnectPopup() {
    tb_show("", "/ClickToConnectPopup.htm?TB_iframe=true&height=410&width=405&modal=true", null, "", true);
}

/* google analytics stuff, delayed to document ready to make page view faster */
function initGa() {
    $.getScript(getGa());
    initGa1();
}
/* google analytics stuff */
function initGa1() {
    if (typeof _gat != "undefined") {
        var pt = _gat._getTracker(gaAct);
        pt._trackPageview();
        return;
    }
    window.setTimeout(initGa1, 100);
}
/* google analytics stuff */
function getGa() {
    var gaJsHost = "";
    try {
        gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");

    }
    catch (x) {
        gaJsHost = "http://www.";
    }
    return gaJsHost + "google-analytics.com/ga.js";
}



/* show the login box*/
function shLogin() {
    $("#login").toggle();
    shLoginBox();
}

/* show the send password dialog*/
function shSendPswd() {
    $("#loginBox").hide();
    $("#loginSendPswd").show();
}

/* send the password*/
function sendPswd() {
    if ($("#username").val() == "") {
        alert("Please enter an email address");
        return;
    }
    $.get("/login.aspx", { what: 1, username: $("#username").val() }, sendPswdReturn, "text");
}

/*send password returned*/
function sendPswdReturn(data) {
    if (data.length > 0) {
        switch (data) {
            case 's':
                $("#loginSendPswd").hide();
                $("#loginPswdSent").show();
                $("#loginPswdSentUsername").html($("#username").val());
                break;
            case 'e':
                alert("Unknown Error");
                break;
            case 'u':
                alert("Unknown username");
                break;
        }
    }
    else {
        alert("Unknown error");
    }
}

/* login was clicked*/
function login() {
    if ($("#user").val() == "") {
        alert("Please enter a Username");
        return;
    }
    if ($("#pass").val() == "") {
        alert("Please enter a Password");
        return;
    }
    $.get("/login.aspx", { what: 0, username: $("#user").val(), pswd: $("#pass").val() }, loginReturn, "text");
}



/* show the login box*/
function shLoginBox() {
    $("#loginBox").show();
    $("#loginSendPswd").hide();
    $("#loginPswdSent").hide();
}

/* login returned*/
function loginReturn(data) {
    if (data.length > 1) {
        set_Cookie("KarastanMembership", data, null);
        shLogin();
        $("#myKarastanLogin").html($("#user").val()).attr("href", "/MyKarastan.aspx");
        if (addType != null) {
            // we were trying to add something
            alert("You are now logged on.\n\nWe noticied you were trying to add something to MyKarastan.\n\nWe will do that now.");
            addToMyKarastan(addType, addId);
        } else {
        alert("You have been logged in.");
            //window.location.reload();
        }
    }
    else {
        alert("Unknown username, or incorrect password");
    }
}

/* Add something to My Karastan*/
function addToMyKarastan(type, id) {
    addType=type;
    addId = id;
    $.get("/MyKarastanAddProduct.aspx", { type: type, id: id }, addToMyKarastanReturn, "text");
}

/* retunr from adding something*/
function addToMyKarastanReturn(data) {
    switch (data) {
        case "0": /*added */
            alert("Adding to MyKarastan successful.");
            addType = null;
            addId = null;
            break;
        case "1": /*Not logged in*/
            alert("You need to have an account and be logged into this Karastan website to add this item to MyKarastan.\n\nAt the top of this page, the login prompt will be displayed.\n\nPlease log in or create an account.");
            shLogin(); 
            break;
        case "2": /*error*/
            alert("An error occurred while trying to add to MyKarastan.\n\nPlease try again soon.");
            break;
    }
}

/* go to the create login page*/
function CreateLogin() {
    if (addType != null) {
        window.location = createPage + "&addType=" + addType + "&addId=" + addId;
    }
    else {
        window.location = createPage;
    }
}

function set_Cookie(name, value, expires, path, domain, secure) {
    var today = new Date();
    today.setTime(today.getTime());

    if (expires) {
        expires = expires * 1000 * 60;
    }
    var expires_date = new Date(today.getTime() + (expires));

    document.cookie = name + "=" + escape(value) +
    ((expires) ? ";expires=" + expires_date.toGMTString() : "") +
    ((path) ? ";path=" + path : "") +
    ((domain) ? ";domain=" + domain : "") +
    ((secure) ? ";secure" : "");
}