var basketID_Display = "basketSummary";
var basketID_Display_Parent = "accountMenuContainer";

var basketID_AddItem = "basketSummary2";
var basketID_AddItem_Parent = ""; //Defined in addAjaxBasket()

function controlLinks(state) {
    var buyLinks = $$(".goldButton");
    for (var i = 0; i < buyLinks.length; i++) {
        if (state == "off") {
            buyLinks[i].addClassName("disabled");
            buyLinks[i].onclick = function () {
                return (false);
            }
        } else if (state == "on") {
            buyLinks[i].removeClassName("disabled");
            basketSummaryInt();
        }
    }
}


var loadingText = "<br /><br /><br /><br /><strong>Loading... Please wait</strong>";
var popUpStatus
popUpStatus = false;
function basketSummaryInt(){
	if (!document.getElementsByTagName) return; 
	var anchors = document.getElementsByTagName("a"); 
	var anchorLength = anchors.length;
	
	for (var i=0; i<anchorLength; i++) { 
		var anchoritem = anchors[i]; 
		var anchorRel = anchoritem.getAttribute("rel");
		
		if(anchoritem.getAttribute("rel")){
			if (anchoritem.getAttribute("href") && anchoritem.getAttribute("rel") == "buyButton") {
				
				anchoritem.onclick = function() {
				    addAjaxBasket(this.href, "");
				    var state = "off"
				    controlLinks(state);
					return(false);
				}
			}

if (anchoritem.getAttribute("href") && anchorRel == "basketSummary") {

				anchoritem.setAttribute("href","javascript:void(0);");
				anchoritem.onmouseover = function(){
					showBasketSummary();	
				}
            }

            //Used for Notify code
            if (anchoritem.getAttribute("href") && anchoritem.getAttribute("rel") == "notifyButton") {
                anchoritem.onclick = function () {
                    if ($("basketSummary2")) {
                        return (false);
                    } else {
                        addNotifyMe(this.href, "");
                        if ($("selSortDD") != null) {
                            $("selSortDD").hide();
                        }
                        var state = "off"
                        controlLinks(state);
                        return (false);
                    }
                }
            }		

		}
	}
}

function getProductID(basketHref){
	var stringArray;
	stringArray = basketHref.split("product=");
	return stringArray[1];
}

/* Open Lightbox for the basket */
function addAjaxBasket(basketHref, commandType) {

    var basketDivHeight = 580; /* value should be put back to 393 after trade in promo */
    var basketDivWidth = 557;
	basketID_AddItem_Parent = $$(".content");
	
    //var updateBasketURL = basketHref.replace("basket.asp","basketAjax.asp")
/*
    new Ajax.Request(addAjaxBasket,{
      method: 'get',
      onSuccess: function(transport) {
          var response = transport.responseText;
          alert("Success! \n\n" + response);
      },
      onFailure: function() {alert('Error')}
  });
*/
	var productId = getProductID(basketHref);
    // Hide flash content
	hideFlashReplacement();

	if(basketID_AddItem_Parent.length > 0){
		basketID_AddItem_Parent = basketID_AddItem_Parent[0];
		
		if(commandType == "removeItem"){
			createBasketSummary(basketID_AddItem, basketID_AddItem_Parent, "removeBasketItem", productId);
		}else{
			createBasketSummary(basketID_AddItem, basketID_AddItem_Parent, "addBasketItem", productId);
		}
	
		// Get viewport height and width
		if (typeof window.innerWidth != 'undefined') {
		  viewPortWidth = window.innerWidth,    
		  viewPortHeight = window.innerHeight,
		  scrollHeight = window.pageYOffset,
		  scrollWidth = window.pageXOffset
		}
		
		// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
		
		else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
		  viewPortWidth = document.documentElement.clientWidth,
		  viewPortHeight = document.documentElement.clientHeight,
		  scrollHeight = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0,
		  scrollWidth = (document.body.parentElement) ? document.body.parentElement.scrollLeft : 0
		}

		// Hide basket
		/*if ($('basketSummary2')){
			document.onclick = function() {
				document.getElementById('basketSummary2').style.display='none'
			}		
		}*/

		$("basketSummary2").style.display = 'block';	
		
		//Place the basket div
		var basketDivTop = ((viewPortHeight - basketDivHeight) / 2) + scrollHeight
		var basketDivLeft = ((viewPortWidth - basketDivWidth) / 2) + scrollWidth
	
		$("basketSummary2").style.top = basketDivTop + "px";
		$("basketSummary2").style.left = basketDivLeft + "px";

		$("basketSummary2").innerHTML = loadingText;

		// setTimeout(function(){closeBasketSummary(basketID_AddItem, basketID_AddItem_Parent)}, 3000);

		// Update basket total at top of page
		var ajaxUpdateTotal;
		ajaxUpdateTotal = new Ajax.Updater('basketTotals', '/store/basketTotalSummary.asp');
		popUpStatus = true;
        
	}
}

function cancelEventBubble(e, id)
{
	var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
	var childItem = false;

	while (reltg.tagName.toLowerCase() != 'body' && (reltg != null || reltg != 'undefined')){
		//	alert(reltg.id);
		if(reltg.id != null){
			if (reltg.id == id){return childItem = true;}
			reltg = reltg.parentNode;
		}
	}
	return childItem = false;
}

function createBasketSummary(summaryID, parentID, summaryType, prodID) {
 

	if(!($(summaryID))){
		var basketSummaryDiv = document.createElement('div');
		basketSummaryDiv.id = summaryID;
		if(!$(parentID)){
			parentID.appendChild(basketSummaryDiv);
		}else{
			$(parentID).appendChild(basketSummaryDiv);
		}
		$(summaryID).style.display = "none";
		getBasketSummaryContents_Ajax(summaryType, prodID);
		$(summaryID).appear({ duration: 0.2 });	
	}else{
		
		$("basketSummary_Prods").fade({duration: 0.4, afterFinish:function(){getBasketSummaryContents_Ajax(summaryType, prodID);}});
	}

}

function showBasketSummary() {
    if (popUpStatus != true) {
        if ($("basketSummary2")) {
            $("basketSummary2").style.display = 'none';
        }
        hideFlashReplacement();
        if (!$(basketID_Display)) {
            createBasketSummary(basketID_Display, "accountMenuContainer", "", "");
        }

        if ($(basketID_Display)) {
            var basketSummaryDiv = $(basketID_Display);
            $("basketSummary").innerHTML = loadingText;
            var childItem = false;
            $(basketID_Display).onmouseout = function (e) {
                if (!e) var e = window.event;
                childItem = cancelEventBubble(e, this.id);
                if (childItem == false) {
                    closeBasketSummary(basketID_Display, "accountMenuContainer");
                }
            }
        }
        // basketSummaryDiv.onclick = function() {
        //     document.location.href='/store/basket.asp'
        // }
        // document.onclick = function() {
        //     $('accountMenu').removeChild(basketSummaryDiv);
        // }
    }
}

function closeBasketSummary(summaryID, parentID) {

	if(!$(parentID)){
		$(summaryID).fade({ duration: 0.2, afterFinish: function(){parentID.removeChild($(summaryID)); swithOnFlash();}});
	}else{
		//alert(summaryID);
		$(summaryID).fade({ duration: 0.2, afterFinish: function(){$(parentID).removeChild($(summaryID)); swithOnFlash();}});
}
popUpStatus = false;
}

function setupButtonsFunction(summaryID, parentID){
	var anchors = document.getElementsByTagName("a"); 
	var anchorLength = anchors.length;
	
	for (var i=0; i<anchorLength; i++) { 
		var anchoritem = anchors[i]; 
		var anchorRel = anchoritem.getAttribute("rel");
		
		if(anchoritem.getAttribute("rel")){
			if (anchoritem.getAttribute("href") && anchorRel.indexOf("removeSummaryBasket|") > -1) {
				anchoritem.onclick = function() {
										
					anchorRel = this.rel;
					relArray = anchorRel.split("|");
					vProduct = relArray[1];
					vModel = relArray[2]

					removeSummaryBasket(this.getAttribute("rel"));
				}
			}

			if (anchoritem.getAttribute("href") && anchoritem.getAttribute("rel") == "btnSummary_Close"){
				anchoritem.onclick = function() {
				    closeBasketSummary(summaryID, parentID);
				    //check if exists first
				    if ($("selSortDD") != null) {
				        $("selSortDD").show();
				    }
				    var state = "on"
				    controlLinks(state);
				}
			}		
		}
	}
}

function removeSummaryBasket(productString){
//	var productID = getProductID(productString);
	var productID = vProduct
	getBasketSummaryContents_Ajax("removeBasketItem", productID);
}

function getBasketSummaryContents_Ajax(summaryType, prodID) {

	var data, ajaxResults;
	//alert("/store/basketSummary_AddBasket.asp?product=" + prodID)
	if(summaryType == "addBasketItem"){
	    //data = "productID=" + prodID;
		//alert("/store/basketSummary_AddBasket.asp?productID=" + prodID)

	    ajaxResults = new Ajax.Updater(basketID_AddItem, "/store/basketSummary_AddBasket.asp?product=" + prodID + "", { onComplete: function() { setupButtonsFunction(basketID_AddItem, basketID_AddItem_Parent); checkPromo(); } });		

	}else if(summaryType == "removeBasketItem"){
//		data = "productID=" + prodID + "&removeItem=true";
		data = "remprod=" + vProduct + "&remmodel=" + vModel + "&removeItem=true";
		url = "/store/basketSummary.asp?remprod=" + vProduct + "&remmodel=" + vModel + "&removeItem=true";
//		ajaxResults = new Ajax.Updater(basketID_Display, "/store/basketSummary.asp", {parameters: data, onComplete:function(){setupButtonsFunction(basketID_Display, basketID_Display_Parent);}});		

		ajaxResults = new Ajax.Updater(basketID_Display, url, {onComplete:function(){setupButtonsFunction(basketID_Display, basketID_Display_Parent);}});		


//		Update basket total at top of page
		var ajaxUpdateTotal;
		ajaxUpdateTotal = new Ajax.Updater('basketTotals', '/store/basketTotalSummary.asp');	

	}else{
	ajaxResults = new Ajax.Updater(basketID_Display, "/store/basketSummary.asp", { onComplete: function() { setupButtonsFunction(basketID_Display, basketID_Display_Parent); checkPromo(); $("basketSummary_Prods").appear({ duration: 0.4 });} });		
	}
}


function checkPromo() {
    if ($('tradeInJune2010')) {
        $('tradeInJune2010').onclick = function() {

            prodID = $('basketProdID').value
            var data = $('frmSurvey').serialize(true);

            //ajaxResults = new Ajax.Request(basketID_AddItem, "/store/basketSummary_UpdateBasket.asp?product=" + prodID + "", {
            ajaxResults = new Ajax.Updater(basketID_AddItem, "/store/basketSummary_UpdateBasket.asp?productUpdated=" + prodID + "", {
                parameters: data,
                onComplete: function() {
                    ajaxUpdateTotal = new Ajax.Updater('basketTotals', '/store/basketTotalSummary.asp');
                    setupButtonsFunction(basketID_AddItem, basketID_AddItem_Parent);
                    //checkPromo();
                }
            });
            return (false);
        }
    }
}
/* Pam Williams  - Start of campaign Notify me code*/

/* Open Lightbox for the Notify */
function addNotifyMe(notifyHref, commandType) {

    var notifyDivHeight = 393;
    var notifyDivWidth = 557;
    basketID_AddItem_Parent = $$(".content");

    var productId = getNotifyProductID(notifyHref);
    var campaignId = getCampaignID(notifyHref);
    //alert("product id = " + productId);
    // Hide flash content
    hideFlashReplacement();
    if (basketID_AddItem_Parent.length > 0) {
        basketID_AddItem_Parent = basketID_AddItem_Parent[0];
        createNotifySummary(basketID_AddItem, basketID_AddItem_Parent, "addNotifyItem", productId, campaignId);
        // Get viewport height and width
        if (typeof window.innerWidth != 'undefined') {
            viewPortWidth = window.innerWidth,
		  viewPortHeight = window.innerHeight,
		  scrollHeight = window.pageYOffset,
		  scrollWidth = window.pageXOffset
        }

        // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

        else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
            viewPortWidth = document.documentElement.clientWidth,
		  viewPortHeight = document.documentElement.clientHeight,
		  scrollHeight = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0,
		  scrollWidth = (document.body.parentElement) ? document.body.parentElement.scrollLeft : 0
        }

        //Place the basket div
        var notifyDivTop = ((viewPortHeight - notifyDivHeight) / 2) + scrollHeight
        var notifyDivLeft = ((viewPortWidth - notifyDivWidth) / 2) + scrollWidth

        $("basketSummary2").style.top = notifyDivTop + "px";
        $("basketSummary2").style.left = notifyDivLeft + "px";
        $("basketSummary2").style.width = "520px";

        $("basketSummary2").innerHTML = '<br /><br /><br /><br /><strong>Loading... Please wait</strong>';
    }


}

function createNotifySummary(summaryID, parentID, summaryType, prodID, campaignID) {
    if (!($(summaryID))) {
        var notifySummaryDiv = document.createElement('div');
        notifySummaryDiv.id = summaryID;
        if (!$(parentID)) {
            parentID.appendChild(notifySummaryDiv);
        } else {
            $(parentID).appendChild(notifySummaryDiv);
        }
        $(summaryID).style.display = "none";
        getNotifySummaryContents_Ajax(summaryType, prodID, campaignID);
        $(summaryID).appear({ duration: 0.2 });
    }

}

function getCampaignID(notifyHref) {
    var stringArray;
    stringArray = notifyHref.split("Campaign_ID=");
    stringArray = stringArray[1].split("&");
    return stringArray[0];
}
function getNotifyProductID(notifyHref) {
    var stringArray;
    stringArray = notifyHref.split("&Product=");

    return stringArray[1];
}
function getNotifySummaryContents_Ajax(summaryType, prodID, campaignID) {

    var data, ajaxResults;

    if (summaryType == "addNotifyItem") {
        ajaxResults = new Ajax.Updater(basketID_AddItem, "/common/campaign/Notify_AddNotify.asp?product=" + prodID + "&CampaignID=" + campaignID + "", { onComplete: function () { setupButtonsFunction(basketID_AddItem, basketID_AddItem_Parent); checkNotify(); } });
    }
}

function checkNotify() {
    if ($('imgContinue')) {
        $('imgContinue').onclick = function () {
            //alert("in check notify");
            var CampaignID;
            var prodID;
            var firstName;
            var lastName;
            var emailAddress;
            var emailConfirmAddress;
            var strFile;
            prodID = $('Product_ID').value;
            CampaignID = $('Campaign_ID').value;
            firstName = $('firstName').value;
            lastName = $('lastName').value;
            emailAddress = $('emailAddress').value;
            emailConfirmAddress = $('emailConfirmAddress').value;
            var blnResult;

            blnResult = false;

            strFile = "/common/campaign/Save_Notify_ajax.asp?CampaignID=" + CampaignID + "&Product=" + prodID + "&firstName=" + firstName + "&lastName=" + lastName + "&emailAddress=" + emailAddress + "&emailConfirmAddress=" + emailConfirmAddress;

            new Ajax.Request(strFile,

                   {
                       method: 'get',
                       onSuccess: function (transport) {
                           var response = transport.responseText || "no response text";

                           if (response == "Success") {
                               ajaxResults = new Ajax.Updater(basketID_AddItem, "/common/campaign/Notify_AddNotify.asp?saved=true", { onComplete: function () { setupButtonsFunction(basketID_AddItem, basketID_AddItem_Parent); checkNotify(); } });
                           }
                           else {
                               ajaxResults = new Ajax.Updater(basketID_AddItem, "/common/campaign/Notify_AddNotify.asp?saved=false", { onComplete: function () { setupButtonsFunction(basketID_AddItem, basketID_AddItem_Parent); checkNotify(); } });
                           }



                       },
                       onFailure: function () { ajaxResults = new Ajax.Updater(basketID_AddItem, "/common/campaign/Notify_AddNotify.asp?saved=false", { onComplete: function () { setupButtonsFunction(basketID_AddItem, basketID_AddItem_Parent); checkNotify(); } }); }
                   });

            return (false);

        }
    }
}

//Pam Williams - this is so that NotifyMe file is added in
//to avoid having to include in other pages that rely on it
//however it doesn't work because prototype thorws an error
function IncludeJavaScript(jsFile) {
    document.write('<script type="text/javascript" src="'
    + jsFile + '"></scr' + 'ipt>');
}
//end of Notify code

document.observe("dom:loaded", function () { basketSummaryInt(); });
