/* 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 + scroll.Y - 175,
        "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 + scroll.Y - 175,
            "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);
}

/**
* 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);

    //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 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
	var	mainImgSrc = getFriendlyUrl("assets/product_images/" + prodObj.image_2_file);
	$("[id$='_QVProductImage']").attr('innerHTML', "<a href=\"" + getFriendlyProductUrl("product.aspx") + "?pf_id=" + prodObj.pf_id 
		+ "\"><img id=\"prod_img\" BORDER=\"0\" VSPACE=\"0\" HSPACE=\"0\" ALT=\"" + prodObj.name 
		+ "\" title=\"" + prodObj.name + "\" src=\"" + mainImgSrc 
		+ "\" onError=\"this.src='App_Themes/Default/images/spacer.gif';\"></a>");

    //Product Detail Link
	$("[id$='_QVProductDetailsLink']").attr('innerHTML', "<a href='" + getFriendlyProductUrl("product.aspx") + "?pf_id=" + prodObj.pf_id 
		+ "'>View Product Detail</a>");

    //Product Share Link
//    $("[id$='_QVProductShareLink']").attr('innerHTML', "<a href='ShareProduct.aspx?pf_id=" + prodObj.pf_id 
//		+ "'>Send To Friend</a>");

    //Product Description
    $("[id$='_QVProductDesc']").attr('innerHTML', prodObj.description);

    var imgContainer = $("#multiTable");
    //var showFlag = false;
    //Alternate Images
	for (i = 1; i <= 5; i++) {
		var returnval = createAlt(imgContainer[0], i);
//		if (returnval != -1)
//			showFlag = true;

	}
//	if (showFlag)
//		$("#multiTable").removeClass("hiddenDiv");

    qvLoader.hide(); // hide loader animation
    qvAction.show();    //show details section

    if (isIE6) {
        //adjust size of iframe
        qvIFrame.height(qvAction.height());
        qvIFrame.width(qvAction.width());
    }
}

/* create alternate images and add to DOM */
function createAlt(imgContainer, imgId) {
	//<img alt="multi_1"  src='' class="QVAlt" onmouseover="swapImg(1);" onerror="this.style.visibility = 'hidden';"  />

	//imgObject.attr('src', alternatesPath + "/" + prodObj.pf_id + "_" + i + "_sm.jpg");
		var altImg = new Image();
		try {
			altImg.src = alternatesPath + "/" + prodObj.pf_id + "_" + i + "_sm.jpg";
			altImg.onmouseover = function() {
				swapImg(imgId);
			}
			altImg.className = "QVAlt block";
			altImg.onerror = function() {
				//$($(this).parent().get(0)).html("");
				$(this).remove();
			}
			
		//	$(imgContainer).html("");
			imgContainer.appendChild(altImg);
			return 1 ;
		}
		catch (e) {
		    // do nothing
		    altImg.remove();
			//$(this).remove();
			return -1;
		}
}

/* image swapper function for alternate images */
   function swapImg(imgToShow) {
   	var imgLgSrc = null;
   	imgLgSrc = alternatesPath + "/" + prodObj.pf_id + "_" + imgToShow + "_lg.jpg";
   	$("#prod_img").attr("src", imgLgSrc);
   }

/* Creates HTML options based on product attributes */
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_value2 + " | " : "") + prodObj.Items[i].attr_value1 + '</option>';
            num_avail++;
        }
    }
    if (num_avail != 0) return options;

    return null;
}

/* Updates the value of selected sku */
function updateQVSku(skuValue) {
    $("[id$='_QVSku']").attr("value", skuValue);
}

/* Show messaging when selected product is not available */
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();
}

/**
* 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());
    }
    //clear out alts
    $("#multiTable").html("");

}


/**
* 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 + '/footnotes/product_json.asp?pf_id=' + pf_id + '&nosattrs=0&noskus=0', true);
    //Use on TS1 - make sure to comment out when putting on server.
    //prodReq.open('GET', 'http://stg5.uniteu.net/footnotes/product_json.asp?pf_id=' + pf_id + '&nosattrs=0&noskus=0', 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();
    }

}