/* Quickview
* Used with - UserControls/css/quickview.css and UserControls/Quickview.ascx
* To use, include ascx, js, and css on page
*      <%@ Register src="UserControls/QuickView.ascx" tagname="QuickView" tagprefix="UU" %>
*      <UU:QuickView ID="QuickView1" runat="server" />
*      <script language="javascript" type="text/javascript" src="App_Themes/Default/js/quickview.js"></script>
*      <link id="Link1" href="UserControls/css/quickview.css" rel="stylesheet" type="text/css" />
*
* Adjust showProd() to change how data is display, but general layout is in the ascx
* Adjust getOptions() to change how options are drawn in sku select
* ***IMPORTANT: Adjust SITESTEM in getProdInfo GET call.!
* *** Set SITESTEM to your actual sitestem on staging server.
*/

/* Set up quick view parameters  */
var prodReq, prodObj; 							// prodReq holds the request object and prodObj holds the returned json object
var isIE = ((navigator.appName) == "Microsoft Internet Explorer") ? true : false; // need this for determining popup positioning
var isIE6 = false; // need this for ajax stuff and whether to display an iframe behind popup

var qvWin = null;       // holds main quickview
var qvIFrame = null;    // to prevent select dropdowns from bleeding through the div
var qvErr = null; 		// holds message to user if they haven't chosen a sku from dropdown to add to basket
var qvAction = null; 	// holds the product form and action buttons (add to cart, wish, view cart)
var qvLoader = null; 	// holds the loading message
var winHeight = 0;

/* Called from the quickview ascx so that the vars are filled after the divs in the ascx are loaded. */
function fillQVVars() {
    /* Load div holder vars with appropriate divs here after they are all loaded */
    if (typeof isQVIE6 != "undefined") isIE6 = true; //isQVIE6 is set in JS in the ascx page with ASP help
    qvWin = $("#QVDiv");
    if (isIE6 == true) { qvIFrame = $("#qv_iframe") } // to prevent select dropdowns from bleeding through the div
    qvErr = $("#qv_error"); 		// holds message to user if they haven't chosen a sku from dropdown to add to basket
    qvAction = $("#qv_action"); 		// holds the product form and action buttons (add to cart, wish, view cart)
    qvLoader = $("#qv_loader"); 		// animated gif for loading
}

$(document).ready(function() {
    //CLOSING POPUP
    //Click the x event!
    $(".QVDivClose").click(function() {
        disablePopup();
    });
    //Press Escape event!
    $(document).keypress(function(e) {
        if (e.keyCode == 27 && popupStatus == 1) {
            disablePopup();
        }
    });
});

//SET UP QV POPUP  
//show popup
function loadPopup() {
    if (isIE6) {
        qvIFrame.show(); //load iframe
    }
    //loads popup only if it is disabled
    if (qvWin.is(':hidden')) {
        qvWin.fadeIn("slow");
    }
}

//disable popup
function disablePopup() {
    //disables popup only if it is enabled
    if (qvWin.is(':visible')) {
        qvWin.fadeOut("slow");
    }
    if (isIE6) {
        qvIFrame.hide(); //hide iframe
    }
}

/**
* Center the QV popup using css
*/
function centerPopup() {
    //request data for centering 
    var windowDim = getWindowSize();
    var popupHeight = $("#QVDiv").height();
    var popupWidth = $("#QVDiv").width();
    var scroll = getScrollXY();
    //centering
    qvWin.css({
        "position": "absolute",
        "top": windowDim.Y / 2 - popupHeight / 2 + scroll.Y - 15,
        "left": windowDim.X / 2 - popupWidth / 2 + scroll.X - 15
    });
    //if IE6 adjust iframe...
    if (isIE6 == true) {
        qvIFrame.css({
            "visibility": "visible",
            "top": windowDim.Y / 2 - popupHeight / 2 + scroll.Y - 15,
            "left": windowDim.X / 2 - popupWidth / 2 + scroll.X - 15
        });
    }
}
/**
* Get position - used for positioning popup
*/
function getScrollXY() {
    var scrOfX = 0, scrOfY = 0;
    if (typeof (window.pageYOffset) == 'number') {
        //Netscape compliant 
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
    } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
        //DOM compliant 
        scrOfY = document.body.scrollTop;
        scrOfX = document.body.scrollLeft;
    } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
        //IE6 standards compliant mode 
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
    }
    return { X: scrOfX, Y: scrOfY };
}
/**
* Get window size - used for positioning popup
*/
function getWindowSize() {
    var myWidth = 0, myHeight = 0;
    if (typeof (window.innerWidth) == 'number') {
        //Non-IE 
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode' 
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible 
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    return { X: myWidth, Y: myHeight }
}

/**
* Sanitizes the PFID since customer has spaces in PFID
*/
function sanitizePfIds(pf_id) {
    var temp = new Array();
    temp = pf_id.split(' ');
    var cleanPfId = "";
    for (var i = 0; i < temp.length; i++) {
        cleanPfId = cleanPfId + temp[i] + "_";
    }
    return cleanPfId.substring(0, cleanPfId.length - 1);
}

/**
* Sanitizes the product name
*/
function sanitizeName(name) {
    //remove specific special characters (see ascii character map for details)
    name = name.toString().replace(/[\x00-\x1F]|[\x21-\x22]|[\x24-\x2C]|[\x2E-\x2F]|[\x3A-\x40]|[\x5B-\x5E]|\x60|[\x7B-\x7F]|[\x80-\x99]/g, '');    

    //change spaces and pluses to -
    name = name.toString().replace(/\+|\s/g,'-');
    
    return name;
}

/**
* Displays the quick view icon when user rolls over the product image
* @param{string} pf_id is used to find the id of the quickview icon image on the page.
**/
function popQVIcon(qv_id) {
    var qvicon = $("#" + qv_id + "");
    qvicon.parent().removeAttr("style");
    qvicon.show();
    qvicon.css("cursor", "pointer");
    qvicon.parent().show();
}

/**
* Hides the quick view icon when user rolls off the product image
* @param{string} pf_id is used to find the id of the quickview icon image on the page.
**/
function hideQVIcon(qv_id) {
    $("#" + qv_id + "").hide();
}

/**
* Populates and displays the quickview window for selected product
**/
function showProd() {
    // check if object has product info before going through all the display stuff

    if (!prodObj.pf_id) {
        // in the rare case there is no product info returned - display a message to user & clear out quickview popup
        showQVError();
        return;
    }

    //////****** Here is where we can fill in the appropriate product information in the QV window  ******//////
    //Product Name
    $("[id$='_QVProductName']").attr('innerHTML', prodObj.name);

    //get clean product name
    var cleanName = sanitizeName(prodObj.name);

    //Product Manufacturer Link
    if (prodObj.vendor_code != "") {
        $("[id$='_QVProductManu']").attr('innerHTML', "by <a class='qvLink' href='" + getFriendlyUrl(prodObj.vendor_code+"/search") + "'>" + prodObj.vendor_code + "</a>");
    }

    //Product Image
    $("[id$='_QVProductImage']").attr('innerHTML', "<a href=\"" + getFriendlyUrl(cleanName + "/" + prodObj.pf_id + "/product") + "\"><img id=\"prod_img\" BORDER=\"0\" VSPACE=\"0\" HSPACE=\"0\" ALT=\"" + prodObj.name + "\" title=\"" + prodObj.name + "\" src=\"http://s7d5.scene7.com/is/image/Lumens/" + prodObj.pf_id + "?$Quickview$\" onError=\"this.src='http://s7d5.scene7.com/is/image/Lumens/product?$Quickview$';\"></a>");

    //Product Detail Link
    $("[id$='_QVProductDetailsLink']").attr('innerHTML', "<a href='" + getFriendlyUrl(cleanName + "/" + prodObj.pf_id + "/product") + "' class='moreInfo'><img src=\"" + getFriendlyUrl("App_Themes/Default/images/Buttons/viewProdQV.gif") + "\" alt=\"View product\" /></a>");

    //Product Share Link
    $("[id$='_QVProductShareLink']").attr('innerHTML', "<a href='" + getFriendlyUrl("ShareProduct.aspx") + "?pf_id=" + prodObj.pf_id + "'><img src=\"" + getFriendlyUrl("App_Themes/Default/images/Buttons/btn_share.gif") + "\" alt=\"Email a friend\" /></a>");

    //Product Description  - display up to the first br tag
    $("[id$='_QVProductDesc']").attr('innerHTML', prodObj.description.substring(0, prodObj.description.toLowerCase().indexOf("<br>")));

    //Procuct Price
    var thePrice = "<p class=\"CallForPrice\">Please call for pricing</p>";
    if (prodObj.list_price_str != "") {
        if (prodObj.msrp_price_str != prodObj.list_price_str) thePrice = "<p>Compare at <font class='msrpPriceDisplay'>" + prodObj.msrp_price_str + "<\/font><\/p>";
        if (prodObj.on_sale == "true" && prodObj.sale_price_str != prodObj.list_price_str) {
            thePrice += "<p>Our Price:&nbsp;<font class=\"ListPricewSale\">" + prodObj.list_price_str + "<\/font><\/p><p>Sale Price:&nbsp;<font class=\"SalePrice\">" + prodObj.sale_price_str + "<\/font><\/p>";
        } else {
            thePrice += "<p>Our Price:&nbsp;<font class=\"ListPricewoSale\">" + prodObj.list_price_str + "<\/font><\/p>";
        }
    }
    $("[id$='_QVProductPrice']").attr("innerHTML", thePrice);

    qvLoader.hide(); // hide loader animation
    qvAction.show();    //show details section

    if (isIE6) {
        //adjust size of iframe
        qvIFrame.height(qvAction.height());
        qvIFrame.width(qvAction.width()+35);
    }
}

/**
* Show error state if something went wrong with Json or with product
**/
function showQVError() {
    //qvWin.height(300);
    if (isIE6) {
        //adjust size of iframe
        qvIFrame.height(qvWin.height());
        qvIFrame.width(qvWin.width());
    }
    qvLoader.hide(); //hide Loader
    qvErr.show(); //show error
}

/**
* Resets quickview window so that it is ready for the next product
**/
function ResetPopup() {
    // clear out divs
    qvErr.hide(); //hide Error section
    qvAction.hide(); //hide Action section
    if (isIE6) {
        //adjust size of iframe
        qvIFrame.height(qvWin.height());
        qvIFrame.width(qvWin.width());
    }
}


/**
* Calls the ajax request for product data
* @param{string} pf_id is sent in the POST to specify which product's data we're requesting
**/
function getProdInfo(pf_id) {
    ResetPopup();

    // display the popup window with a 'loading' message to user until the product info has been loaded
    qvLoader.show();

    if (isIE6) { qvIFrame.show(); }

    if (!isIE6) { // iIE7, Mozilla, Safari, ...
        prodReq = new XMLHttpRequest();
    } else { // IE6, below
        prodReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //centering with css
    centerPopup();
    //load popup
    loadPopup();

    /* determine page protocol */
    var myTemp = window.location.href;
    var tempSplit = myTemp.split(":");
    var pageProt = tempSplit[0];

    /*** IMPORTANT ***/
    //Use on actual server - make sure to comment out when using this on TS1
    prodReq.open('GET', document.location.protocol+'//'+document.location.hostname+'/lumens/product_json.asp?pf_id='+pf_id+ '&nosattrs=1&noskus=1', true);
    //Use on TS1 - make sure to comment out when putting on server.
    //prodReq.open('GET', 'http://stg5.uniteu.net/lumens/product_json.asp?pf_id=' + pf_id + '&nosattrs=1&noskus=1', true);

    prodReq.setRequestHeader('Content-type', 'application/xml');
    prodReq.onreadystatechange = function() { productCallback(); } // specify our callback function
    prodReq.send(null);
}

/**
* Callback function called in getProdInfo, catches errors or bad statuses that may be returned
**/
function productCallback() {
    try {
        if (prodReq.readyState == 4) {	// 4 = complete
            prodObj = eval('(' + prodReq.responseText + ')'); // parse returned json object for our javascript to read
            showProd(); // call functino to display product /quickview window
            if (prodReq.status != 200) {
                //alert('status != 200');
                return;
            }
        }
        else {
            // So IE won't throw an error
            return;
        }
    } catch (e) {
        // improperly formed json
        showQVError();
    }

}