/* 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 = (window.ActiveXObject) ? true : false; // need this for ajax stuff and whether to display an iframe behind popup
var qvWin = $("#QVDiv");
if (isIE6) { var qvIFrame = $("#qv_iframe"); } // to prevent select dropdowns from bleeding through the div
var qvErr = $("#qv_error"); 		// holds message to user if they haven't chosen a sku from dropdown to add to basket
var qvAction = $("#qv_action"); 		// holds the product form and action buttons (add to cart, wish, view cart)
//var qvLoader = $("#qv_loader");			// (moosejaw specific) animated gif for loading
var winHeight = 0;

//SET UP QV POPUP  
//show popup
function loadPopup() {
    //loads popup only if it is disabled
    if (qvWin.is(':hidden')) {
        qvWin.fadeIn("fast");
    }
}

//disable popup
function disablePopup() {
    //disables popup only if it is enabled
    if (qvWin.is(':visible')) {
        qvWin.fadeOut("slow");
    }
}

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 };
}

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 }
}

//center popup
function centerPopup() {
    //request data for centering 
    var windowDim = getWindowSize();
    var popupHeight = $("#QVDiv").height();
    var popupWidth = $("#QVDiv").width();
    var scroll = getScrollXY();
    //centering
    $("#QVDiv").css({
        "position": "absolute",
        "top": windowDim.Y / 2 - popupHeight / 2 + scroll.Y - 5,
        "left": windowDim.X / 2 - popupWidth / 2 + scroll.X - 15
    });
    //only need force for IE6
}

$(document).ready(function() {
    //LOADING POPUP
    //Click the button event!
    //DONT DO THIS HERE OR YOU HAVE TO WAIT FOR THE PAGE TO LOAD BEFORE YOU CAN GET A QV TO APPEAR
    $("img.qvicon").click(function() {
        //centering with css
        centerPopup();
        //load popup
        loadPopup();
    });

    //CLOSING POPUP
    //Click the x event!
    $(".QVDivClose").click(function() {
        disablePopup();
    });
    //Press Escape event!
    $(document).keypress(function(e) {
        if (e.keyCode == 27) {
            disablePopup();
        }
    });

});


/**
* Draws quick view icon div near product thumbnail
*/
function draw_qv_div(product_pfid) {
    document.write("<div class=\"qv-wrapper\" style=\"display:none;\">");
    document.write("<img src=\"App_Themes/Default/images/qvicon.gif\" class=\"qvicon\" ");
    if (window.XMLHttpRequest) { document.write("style=\"left:0px;\" "); } // add in an ie7 hack
    document.write("id=\"qvicon_" + product_pfid + "\" ");
    document.write("onmouseover=\"popQVIcon('qvicon_" + product_pfid + "');\" ");
    document.write("onclick=\"getProdInfo('" + product_pfid + "');\" ");
    document.write("onmouseout=\"hideQVIcon('qvicon_" + product_pfid + "');\" /></div>");
}

/**
* 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.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() {

    /* Make sure these vars are filled again here so that first call to qv doesn't show up blank */
    qvWin = $("#QVDiv");
    if (isIE6) { 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");
    qvRight = $("#qv_right");
    qvBtns = $("#qv_buttons");

    // check if object has product info before going through all the display stuff
    //console.log(prodObj.pf_id == null || prodObj.pf_id == "");
    if (prodObj.pf_id == null || prodObj.pf_id == "") {
        qvRight.hide();
        qvBtns.hide();
        qvErr.show();
        
        // in the rare case there is no product info returned - display a message to user & clear out quickview popup
        qvWin.css({ height: "300px" });
        if (isIE6) { qvIFrame.css({ height: "300px" }); }

        qvWin.show();
        return;
    } else {
        qvErr.hide();
        qvRight.show();
        qvBtns.show();
    }


    //////****** Here is where we can fill in the appropriate product information in the QV window  ******//////
    //Product Name
    $("[id$='_QVProductName']").attr('innerHTML', prodObj.name);

    //Procuct Price
    $("[id$='_QVProductPrice']").attr('innerHTML', (prodObj.on_sale == "true") ? "<font class='ListPricewoSale'>Regular Price&nbsp;" + prodObj.list_price_str + "</font><br><font class='SalePrice'>Sale&nbsp;" + prodObj.sale_price_str + "</font>" : "<font class='ListPricewoSale'>Price&nbsp;" + prodObj.list_price_str + "</font>");

    // Product Description
    $("[id$='_QVDesc']").attr('innerHTML', prodObj.short_description);
    
    //Product Attributes
    if (prodObj.Items.length >= 1) { //if there is more than 1 sku...
        //set sku value to first sku
        updateQVSku(prodObj.Items[0].sku);
        if (prodObj.Items.length == 1) { //if there is only 1 sku...
            $("select#QVSkuSelect").hide();
            if (prodObj.Items[0].avail != "0") { //if the only sku is available...
                handleAvail();
                $("[id$='_QVAvailMsg']").attr('innerHTML', " " + prodObj.Items[0].attr_value1);
                $("[id$='_QVAvailMsg']").show();
                $("select#QVSkuSelect").hide();
            } else {//only sku is not available
                handleUnAvail();
            }
        } else { //there are many skus
            //get options
            var skuOptions = getOptions();
            if (skuOptions != null) { //if options not null...
                // fill select
                $("select#QVSkuSelect").html(skuOptions);
                handleAvail();
            } else { //options are null
                //no items are available
                handleUnAvail();
            }
        }
    }

    //Product Image
    $("[id$='_QVProductImage']").attr('innerHTML', "<img src=\"http://s7d2.scene7.com/is/image/MarissaCollections/" + prodObj.pf_id + "?$s7search$\" alt=\"" + prodObj.name + "\" onerror=\"this.src = 'http://s7d2.scene7.com/is/image/MarissaCollections/Coming_Soon?$s7search$';\" title=\"" + prodObj.name + "\" /></a>");
    //$("[id$='_QVProductImage']").attr('innerHTML', "<a href=\"product.aspx?pf_id=" + prodObj.pf_id + "\"><img id=\"prod_img\" BORDER=\"0\" VSPACE=\"0\" HSPACE=\"0\" ALT=\"" + prodObj.name + "\" title=\"" + prodObj.name + "\" src=\"assets/product_images/" + prodObj.image_2_file + "\" onError=\"this.src='App_Themes/Default/images/spacer.gif';\"></a>");

    //Product Detail Link
    $("[id$='_QVProductDetailsLink']").attr('innerHTML', "<a href='Product.aspx?pf_id=" + prodObj.pf_id + "'><img src=\"App_Themes/Default/images/buttons/btn_detail.gif\" alt=\"product details\" /></a>");

    //Product Share Link
    $("[id$='_QVProductShareLink']").attr('innerHTML', "<a href='ShareProduct.aspx?pf_id=" + prodObj.pf_id + "'><img src=\"App_Themes/Default/images/buttons/btn_emailfriend.gif\" alt=\"email a friend\" /></a>");

    winHeight = 600;
    //make height 215 + height of image
    if (document.getElementById("prod_img")) {
        var img = document.getElementById("prod_img");
        winHeight = img.height + 215;
    }

    if (isIE6) {	// make iframe visible if IE
        qvIFrame.style.height = (winHeight - 50) + "px";
        qvIFrame.show();
        qvIFrame.style.zIndex = "9999979";
    }

    centerPopup();
    //load popup
    loadPopup();
    //qvLoader.hide();	// hide loader animation	
    qvWin.show(); // finally display the product quickview popup on the page

}

function getOptions() {
    var num_avail = 0;

    //get options to put into select
    var options = "";
    for (var i = 0; i < prodObj.Items.length; i++) {
        if (prodObj.Items[i].avail != "0") {
            options += '<option value="' + prodObj.Items[i].sku + '">' + prodObj.Items[i].attr_value2 + " | " + prodObj.Items[i].attr_value1 + '</option>';
            num_avail++;
        }
    }
    if (num_avail != 0) return options;

    return null;
}

function updateQVSku(skuValue) {
    $("[id$='_QVSku']").attr("value", skuValue);
}

function handleUnAvail() {

    //Show unavail message
    $("[id$='_QVAvailMsg']").attr('innerHTML', "So sorry but this product is not available.");
    $("[id$='_QVAvailMsg']").show();

    //hide select and labels
    $("select#QVSkuSelect").hide();
    $("[id$='_QVAttrLabel']").hide();
    $("[id$='_QVQuantity']").hide();
    $("[id$='_QVQtyLabel']").hide();
    //hide buttons
    $("[id$='_QVAddToCart']").hide();
    $("[id$='_QVAddToCart1']").hide();
}

function handleAvail() {
    //hide unavail message
    $("[id$='_QVAvailMsg']").attr('innerHTML', "");
    $("[id$='_QVAvailMsg']").hide();

    //show select and labels
    $("select#QVSkuSelect").show();
    $("[id$='_QVAttrLabel']").show();
    $("[id$='_QVQuantity']").show();
    $("[id$='_QVQtyLabel']").show();
    //show buttons
    $("[id$='_QVAddToCart']").show();
    $("[id$='_QVAddToCart1']").show();
}

/**
* Closes and clears out the product quickview window so that it is ready for the next product
**/
function closeProd() {
    // clear out divs
    qvErr.hide();
    qvAction.innerHTML = "";
    qvWin.hide(); 	// hide quickview popup
    if (qvIFrame) { qvIFrame.hide(); } // hide iframe
}


/**
* 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) {
    if (qvWin.is(':visible')) { closeProd(); }

    // display the popup window with a 'loading' message to user until the product info has been loaded
    //qvLoader.style.display = "block";

    if (isIE6) { qvIFrame.show(); }

    if (!isIE6) { // iIE7, Mozilla, Safari, ...
        prodReq = new XMLHttpRequest();
        isIE6 = false;
    } else { // IE6, below
        prodReq = new ActiveXObject("Microsoft.XMLHTTP");
        isIE6 = true;
    }
    qvWin.show();

    /* 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 + '/marissa/product_json.asp?pf_id=' + pf_id + '&inventory=1', true);
    //Use on TS1 - make sure to comment out when putting on server.
    //prodReq.open('GET', 'http://stg5.uniteu.net/marissa/product_json.asp?pf_id=' + pf_id + '&inventory=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
    }

}

