﻿var btnBack = document.getElementById('ctl00_btnBack')
if (!btnBack)
    btnBack = parent.document.getElementById('ctl00_btnBack')

var btnContinue = document.getElementById('ctl00_btnContinue')
if (!btnContinue)
    btnContinue = parent.document.getElementById('ctl00_btnContinue')

// Cookies
function createCookie(name,value,days) {
    var expires = ""
    if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	}
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') {
		    c = c.substring(1,c.length)
		}
		if (c.indexOf(nameEQ) == 0) {
			return c.substring(nameEQ.length,c.length);
		}
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

// LineItems class
function JLineItems(updatingBuyCounts) {    
    this.productLineItems = new Array()
    this.menuLineItems = new Array()
    if (!updatingBuyCounts) {
        var cookie = readCookie('JLineItems')
        if (cookie) {
            var splitCookie = cookie.split('-')
            var products = splitCookie[0].split('|')
            var menus = splitCookie[1].split('|')
            for (var i = 0; i < products.length; i++) {
                if (products[i].length > 0)
                    this.productLineItems.push(products[i])
            }
            for (var i = 0; i < menus.length; i++) {
                if (menus[i].length > 0)
                    this.menuLineItems.push(menus[i])
            }
        }
    }
    
    this.addProduct = function(productID, buyCount) {
        this.productLineItems.push(productID + ',' + buyCount)
    }
    
    this.addMenu = function(menuID, productsCommaDelimStr, buyCount) {
        // Remove any excess comma from the deliminated products string
        if (productsCommaDelimStr.charAt(productsCommaDelimStr.length - 1) == ',') {   
            productsCommaDelimStr = productsCommaDelimStr.substr(0, productsCommaDelimStr.length - 1)
        }
        
        var newMenuStr = menuID + ',' + buyCount + ',' + productsCommaDelimStr
        
        // Delete any already added menu that matches
        for (var i = 0; i < this.menuLineItems.length; i++) {
            var splitItemExisting = this.menuLineItems[i].split(',')
            var splitItemNew = newMenuStr.split(',')
            if (splitItemExisting[0] == splitItemNew[0] && splitItemExisting.length == splitItemNew.length) {
                // Same menuID and product count. Check contents
                // But start creating the new menu string with summed buycount just in case
                var newMenuStrWithNewBuyCountSum = splitItemNew[0] + ',' + (parseInt(splitItemExisting[1]) + parseInt(splitItemNew[1])) + ','
                var match = true
                for (var j = 2; j < splitItemExisting.length; j++) {
                    if (splitItemExisting[j] == splitItemNew[j]) {
                        newMenuStrWithNewBuyCountSum += splitItemNew[j]
                        if (j < splitItemExisting.length - 1) {
                            newMenuStrWithNewBuyCountSum += ','
                        }
                    }
                    else {
                        match = false
                        break
                    }
                }
                
                if (match) {
                    this.menuLineItems.remove(this.menuLineItems[i])   
                    newMenuStr = newMenuStrWithNewBuyCountSum
                }
            }
        }
        
        this.menuLineItems.push(newMenuStr)
    }
    
    this.save = function() {
        var products = ''
        for (var i = 0; i < this.productLineItems.length; i++) {
            products += this.productLineItems[i]
            if (i < this.productLineItems.length - 1) {
                products += '|'                
            }
        }
    
        var menus = ''
        for (var i = 0; i < this.menuLineItems.length; i++) {
            menus += this.menuLineItems[i]
            if (i < this.menuLineItems.length - 1) {
                menus += '|'                
            }
        }
        
        if (products.length > 0 || menus.length > 0) {
            // Example: 34,3|56,55,P42|2,M8,37,76,89;1,M9,62,34;
            // PID,BuyCount|PID,BuyCount-MID,BuyCount,PID,PID,PID|MID,BuyCount,PID,PID
            createCookie('JLineItems', products + '-' + menus, 1)
        }
        else {
            eraseCookie('JLineItems')
        }
    }
}

function UpdateTotalItems(IsConfirmationPage) {
    var TotalItems = 0;
    var TotalCost = 0;
    var lineItems = new JLineItems(true) // Selected products/menus and counts
    
    // Go through all textboxes and add up the totals
    for (var i = 0; i < document.frmOrder.elements.length; i++) {
        var ProductTotal = 0;
        
        var E = document.frmOrder.elements[i];
        if (E.type == 'text' && E.getAttribute('IgnoreInTotal') == null) {
            E.value = trim(E.value)
            var Price = parseFloat(E.getAttribute('Price')); // Price is saved here in code behind
            
            if (isNumericInt(E.value) && !isNaN(Price)) {
                var BuyCount = parseInt(E.value);
                E.value = BuyCount // In case they write '01'. This changes it to '1'
                if (BuyCount > 0) {
                    TotalItems += BuyCount;
                    TotalCost += BuyCount * Price;
                    // Add to line items
                    if (E.getAttribute('MenuID')) {
                        lineItems.addMenu(E.getAttribute('MenuID'), E.getAttribute('ProductIDs'), BuyCount)
                    }
                    else {
                        lineItems.addProduct(E.getAttribute('ProductID'), BuyCount)
                    }
                    
                    // If it's the confirmation page, add up product totals
                    if (IsConfirmationPage) {
                        ProductTotal = BuyCount * Price;
                    }
                }
            }
            else {
                E.value = '';
            }
            
            if (IsConfirmationPage) {
                document.getElementById(E.getAttribute('TotalPriceControlID')).innerHTML = ProductTotal;
            }
        }
    }
              
    // Update totals
    if (!IsConfirmationPage) {
        parent.document.getElementById('TotalItems').innerHTML = TotalItems;
        parent.document.getElementById('TotalCost').innerHTML = TotalCost;
    }
    else {
        // If showing delivery price, include it in the total cost
        if (document.getElementById('trDeliveryLine').style.display == '') {
            TotalCost += parseFloat(document.getElementById('DeliveryPrice').innerHTML)
        }
        document.getElementById('TotalCost').innerHTML = TotalCost;
    }
    
    if (!IsConfirmationPage) {
        SetButtonEnabling(btnContinue, (TotalItems > 0))
    }
    else {
        SetButtonEnabling(btnContinue, (TotalItems > 0 && document.getElementById('radPickup').checked || document.getElementById('trDeliveryLine').style.display == '')) 
    }
    
    lineItems.save()
}

function isNumericInt(sText) {
    if (sText.length > 0) {
        var validChars = "0123456789"; 
        for (var i = 0; i < sText.length; i++) {
            if (validChars.indexOf(sText.charAt(i)) == -1) {
                return false;
            }
        }
        return true;
    }
    else {
        return false;
    }
}

function DoMoveForward(Me) {
    if (Me.className.indexOf('disabled') > -1) {
        return false;
    }
    else {
        //PostBackAnyIframe();
        if (document.location.pathname.toLowerCase().indexOf('selectmenus.aspx') > -1) {
            // Add new menu
            var menuLineItems = new JLineItems(false)
            menuLineItems.addMenu(document.getElementById('ctl00_Content_hdnMenuID').value, document.getElementById('ctl00_Content_hdnProductIDs').value, document.getElementById('ctl00_Content_hdnBuyCount').value)
            menuLineItems.save()
        }
        
        // If there's a validate button in the page we want to click that instead of the bottom continue
        var validateButton = document.getElementById('ctl00_Content_btnValidate')
        if (validateButton) {
            validateButton.click()
            return false
        }
        else {
            return true
        }
    }
}

function SetButtonEnabling(Button, Enable) {
    if (Enable) {
        //Button.style.visibility = 'visible'
        //Button.disabled = ''
        if (Button.className.indexOf('button1') > -1) {
            Button.className = 'button1'
        }
        else {
            Button.className = 'button2'
        }
    }
    else {
        //Button.style.visibility = 'hidden'
        //Button.disabled = 'disabled'
        if (Button.className.indexOf('button1') > -1) {
            Button.className = 'button1_disabled'
        }
        else {
            Button.className = 'button2_disabled'
        }
    }
}
       
function trim(str){
    while (str.substring(0,1) == ' ') {
        str = str.substring(1, str.length);
    }
    while (str.substring(str.length-1, str.length) == ' ') {
        str = str.substring(0, str.length-1);
    }
    return str;
}
       
function imageViewer(oThis, iState, oEvt, imgSrc){
    var oBig = oThis.parentNode.getElementsByTagName("div")[1];
    var previewArea = document.getElementById("previewArea");
    var imgProductLarge = oBig.getElementsByTagName('img')(0)
    
    var e = oEvt || window.event;
    if (e.pageX || e.pageY) {
        posx = e.pageX;
	    posy = e.pageY;
	}
	else if (e.clientX || e.clientY) {
	    posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
	    posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
	}
	// posx and posy contain the mouse position relative to the document
        	        	
	if (iState){ // on mouseover
	    if (e.clientY < (getBrowserHeight()/2)) {
	    	//oBig.style.backgroundImage = "url(Images/foldout_bottom)";
		    oBig.style.top = 0;
	    }
	    else {
	        //oBig.style.backgroundImage = "url(Images/foldout_top)";
		    oBig.style.top = -oBig.clientHeight+"px";
	    } 
	    oThis.style.borderColor = "black";
	    oBig.style.visibility = "visible";
	    imgProductLarge.src = imgSrc
	}
	else { // on mouseout
	    oThis.style.borderColor = "";
	    oBig.style.visibility = "hidden";
	}
}

/*
function PostBackAnyIframe(){
    if (document.frames[0]) {
        document.frames[0].document.forms[0].submit()
    }
    return false
}
*/

function DoSIFRReplace(){
    if(typeof sIFR == "function"){
        var MyriadProBold = "sIFR/MyriadProLight.swf"
        var MyriadProNormal = "sIFR/MyriadPro.swf"
        // Changes to styles here should be reflected in the stylesheet
        // Especially paddings must match exactly, or text isn't scaled properly
        var TopMenuPaddingTop = "7"
        var NearWhite = "#f6f6f6"
        var NearBlack = '#3e3e3e'
        var UmamiColor = '#f69026'
        
        sIFR.replaceElement(named({sSelector:"h1.TopMenu", sFlashSrc:MyriadProBold, sColor:NearWhite, sWmode:"transparent", nPaddingTop:TopMenuPaddingTop, sFlashVars:"textalign=center"}));
        sIFR.replaceElement(named({sSelector:"h1.TopMenuSelected", sFlashSrc:MyriadProBold, sColor:"#383838", sWmode:"transparent", nPaddingTop:TopMenuPaddingTop, sFlashVars:"textalign=center"}));
        sIFR.replaceElement(named({sSelector:"h1.BottomNumber", sFlashSrc:MyriadProBold, sColor:NearWhite, sWmode:"transparent", sFlashVars:"textalign=left"}));
        sIFR.replaceElement(named({sSelector:"h1.Headline, h1.SubHeadline", sFlashSrc:MyriadProBold, sColor:NearBlack, sWmode:"transparent", sFlashVars:"textalign=left"}));
        sIFR.replaceElement(named({sSelector:"h1.HeadlineBlack, h1.SubHeadlineBlack", sFlashSrc:MyriadProBold, sColor:"#000000", sWmode:"transparent", sFlashVars:"textalign=left"}));
        sIFR.replaceElement(named({sSelector:"h1.HeadlineCenter, h1.SubHeadlineCenter", sFlashSrc:MyriadProBold, sColor:NearBlack, sWmode:"transparent", sFlashVars:"textalign=center"}));
        sIFR.replaceElement(named({sSelector:"h1.HeadlineRight, h1.SubHeadlineRight", sFlashSrc:MyriadProBold, sColor:NearBlack, sWmode:"transparent", sFlashVars:"textalign=right"}));
        sIFR.replaceElement(named({sSelector:"h1.LeftMenuHeadline", sFlashSrc:MyriadProBold, sColor:UmamiColor, sWmode:"transparent", sFlashVars:"textalign=right"}));
        sIFR.replaceElement(named({sSelector:"h1.FrontPagePanelHeadline", sFlashSrc:MyriadProBold, sColor:"#000000", sWmode:"transparent", sFlashVars:"textalign=left"}));
        sIFR.replaceElement(named({sSelector:"h1.FrontPagePanel", sFlashSrc:MyriadProNormal, sColor:"#000000", sWmode:"transparent", sFlashVars:"textalign=left"}));
    }
}

function getBrowserWidth() {
    if (navigator.userAgent.indexOf("MSIE") > 0)
        return document.body.clientWidth
    else
        return window.outerWidth
}

function getBrowserHeight() {
    if (navigator.userAgent.indexOf("MSIE") > 0)
        return document.body.clientHeight
    else
        return window.outerHeight
}

function getBrowserLeft() {
    if (window.screenLeft)
        return window.screenLeft
    else
        return window.screenX
}

function getBrowserTop() {
    if (window.screenTop)
        return window.screenTop
    else
        return window.screenY
}

function openPopup(url, width, height) { 
	// Get center of browser window
    var X = getBrowserWidth() / 2
    var Y = getBrowserHeight() / 2
 
    var Left = (getBrowserLeft() + (X - (width / 2)))
    var Top = (getBrowserTop() + (Y - (height / 2)))
                    	
    config = ""
    config += "left=" + Left + ","
    config += "top=" + Top + ","
    config += "toolbar=no,"
    config += "location=no,"
    config += "directories=no,"
    config += "status=no,"
    config += "menubar=no,"				// Not on Apple Mac for obvious reasons
    config += "scrollbars=yes,"
    config += "resizable=no,"			// Mac windows are always resizable
    config += "copyhistory=no,"
    config += "width=" + width + ","
    config += "height=" + height
    var win = open(url, "", config)
    if (win){
        win.focus()
    }
}

function Querystring(qs) { // optionally pass a querystring to parse
	this.params = new Object()
	this.get=Querystring_get
	
	if (qs == null)
		qs=location.search.substring(1,location.search.length)

	if (qs.length == 0) return

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ')
	var args = qs.split('&') // parse out name/value pairs separated via &
	
// split out each name=value pair
	for (var i=0;i<args.length;i++) {
		var value;
		var pair = args[i].split('=')
		var name = unescape(pair[0])

		if (pair.length == 2)
			value = unescape(pair[1])
		else
			value = name
		
		this.params[name] = value
	}
}

function Querystring_get(key, default_) {
	// This silly looking line changes UNDEFINED to NULL
	if (default_ == null) default_ = null;
	
	var value=this.params[key]
	if (value==null) value=default_;
	
	return value
}