// Future Shop
Sys.Application.add_load(initializePersonal);

function readCookieName(name) {
    if (document.cookie) {
        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 IsNullOrEmpty(str) {
    if (str == "" || str == null || str == "null" || str == 'undefined')
        return true;
    else
        return false;
}

function writeCookie(name, value) {
	var expirationDate = new Date();
	expirationDate.setHours(expirationDate.getHours() + 1);
	document.cookie = name + "=" + value + ";expires=" + expirationDate.toGMTString() + ";path=/";
}

Type.registerNamespace("BestBuy.Mccp.Commerce.WebSite.FutureShopCanada");

BestBuy.Mccp.Commerce.WebSite.FutureShopCanada.UserInformation = function() {
}

BestBuy.Mccp.Commerce.WebSite.FutureShopCanada.UserInformation.prototype = {
	FirstName: "",
	Shortened: "...",
	IsAuthenticated: false,
	IsRecognized: false,
	CartItems: 0,
	WishListItems: 0,
	CartTotal: "",

	get_FirstName: function() {
		if (this.FirstName.length > profile_WelcomeNameLength)
			return this.FirstName.substring(0, profile_WelcomeNameLength - this.Shortened.length) + this.Shortened;
		else
			return this.FirstName;
	},
	
	set_IsAuthenticated: function(value) {
		this.IsAuthenticated = value;		
		this.raisePropertyChanged('IsAuthenticated');
	},

	get_IsAuthenticated: function() {
		return this.IsAuthenticated;
	},
	PersonalInformationHandler: function(result, userContext, methodName) {
		this.FirstName = result.FirstName;
		this.IsAuthenticated = result.IsAuthenticated;
		this.IsRecognized = result.IsRecognized;
		this.CartItems
	},

	PageLoadHandler: function() {
		if (typeof (BestBuy.Mccp.Commerce.WebSite.FutureShopCanada.ProfileService) == "undefined") return;

		BestBuy.Mccp.Commerce.WebSite.FutureShopCanada.ProfileService.GetUserInformation(UserInformationSucceeded)
		
		var handlerPriceWatch = userInformation.get_events().getHandler('UpdatePriceWatch');
		if (handlerPriceWatch) handlerPriceWatch(userInformation, Sys.EventArgs.Empty);

		var nCartItems = readCookieName("CartItems");
		if (nCartItems == null)
			BestBuy.Mccp.Commerce.WebSite.FutureShopCanada.ProfileService.GetQuickCartInformation(QuickCartInformationSucceeded);
		else {
			this.CartItems = nCartItems;
			this.CartTotal = readCookieName("CartTotal");
			if (this.CartTotal == null)
				this.CartTotal = "";
			this.WishListItems = readCookieName("WishListItems");
			if (this.WishListItems == null)
				this.WishListItems = 0;
			var handler = userInformation.get_events().getHandler('QuickCartInformationUpdated');
			if (handler) handler(userInformation, Sys.EventArgs.Empty);
		}
	}
}


BestBuy.Mccp.Commerce.WebSite.FutureShopCanada.UserInformation.registerClass('BestBuy.Mccp.Commerce.WebSite.FutureShopCanada.UserInformation', Sys.Component, Sys.IDisposable);

userInformation = new BestBuy.Mccp.Commerce.WebSite.FutureShopCanada.UserInformation()

function initializePersonal() {
	userInformation.PageLoadHandler();
}

if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

function SetUserInformation(firstName, isAuthenticated) {
    userInformation.FirstName = firstName;
    userInformation.IsAuthenticated = isAuthenticated;

    if (!userInformation.IsAuthenticated) {
        userInformation.FirstName = readCookieName("FirstName");
        if (IsNullOrEmpty(userInformation.FirstName)) {
            userInformation.IsRecognized = false;
        }
        else {
            userInformation.IsRecognized = true;
        }
    }
    var handler = userInformation.get_events().getHandler('UserInformationUpdated'); if (handler) handler(userInformation, Sys.EventArgs.Empty);
}

function UserInformationSucceeded(result, userContext, methodName) {
    SetUserInformation(result.FirstName, result.IsAuthenticated);
	if (userInformation.IsAuthenticated)
	    writeCookie("FirstName", userInformation.FirstName);	
}

function QuickCartInformationSucceeded(result, userContext, methodName) {
	userInformation.CartItems = result.NumberOfItemsInCart;
	userInformation.CartTotal = result.CartTotal;
	userInformation.WishListItems = result.NumberOfItemsInWishList;
	writeCookie("CartItems", result.NumberOfItemsInCart);
	writeCookie("CartTotal", result.CartTotal);
	writeCookie("WishListItems", result.NumberOfItemsInWishList);
	var handler = userInformation.get_events().getHandler('QuickCartInformationUpdated');
	if (handler) handler(userInformation, Sys.EventArgs.Empty);
}
function UpdateWelcomeUC() {
    var firstName;
    if (userInformation.IsAuthenticated) {
        $get("Authenticated").style.display = "block";
        firstName = userInformation.get_FirstName();
        setText("LblAuthenticatedFirstName", firstName);
        setText("LblRecognizedFirstName2", firstName);       
    }
    else if (userInformation.IsRecognized) {
        $get("Recognized").style.display = "block";
        firstName = userInformation.get_FirstName();
        setText("FirstNameLabel", firstName);
        setText("LblRecognizedFirstName1", firstName);            
    }
    else {
        $get("NotRecognized").style.display = "block";
    }
}
function UpdateWelcomeUCFromCookie() {
    var firstName = readCookieName("FirstName");
    if (firstName != null)
        firstName = unescape(firstName);
        
    var firstNameLength = document.getElementById("ctl00_MainHeader_ctl00_uchead_ucWelcome_HfdFirstNameLength").value;
    if (firstName != null && firstName.length > firstNameLength) {
        firstName = firstName.substring(0, 6) + "...";
    }
    var recognized = readCookieName("Recognized");


        
    if (firstName == null || recognized == '') {
        $get("NotRecognized").style.display = "block";
    }
    else {
        $get("Authenticated").style.display = "block";
        setText("LblAuthenticatedFirstName", firstName);
        setText("LblRecognizedFirstName2", firstName);
    }
}
function setText( objName, objText )
{
  if(document.all) {
    $get(objName).innerText = objText;
  }
  else {
    $get(objName).textContent = objText;
  }
}

var isNN = (navigator.appName.indexOf("Netscape") != -1);

function autoTab(input, len, e) {
	var keyCode = (isNN) ? e.which : e.keyCode;
	var filter = (isNN) ? [0, 8, 9] : [0, 8, 9, 16, 17, 18, 37, 38, 39, 40, 46];
	if (input.value.length >= len && !containsElement(filter, keyCode)) {
		input.value = input.value.slice(0, len);
		input.form[(getIndex(input) + 1) % input.form.length].focus();
		input.form[(getIndex(input) + 1) % input.form.length].select()
	}

	function containsElement(arr, ele) {
		var found = false, index = 0;
		while (!found && index < arr.length)
			if (arr[index] == ele)
			found = true;
		else
			index++;
		return found;
	}

	function getIndex(input) {
		var index = -1, i = 0, found = false;
		while (i < input.form.length && index == -1)
			if (input.form[i] == input) index = i;
		else i++;
		return index;
	}
	return true;
}

function countryChanged(country, lblStateClientId, lblZipClientId, ddlStateClientId) {
	var data = countryData[country];
	if (!data) return true;
	$get(lblStateClientId).innerHTML = data.stateLabel;
	$get(lblZipClientId).innerHTML = data.zipLabel;
	var selStates = $get(ddlStateClientId);
	selStates.options.length = 0;
	for (var i = 0; i < data.states.length; i++) {
		selStates.options[i] = new Option(data.states[i].name, data.states[i].code);
		if (data.states[i].code == '0')
			selStates.selectedIndex = i;
	}
	return false;
}
