//DEBUG
//travellingPreference = "0";

//Global vars
var screenwidth;
var screenheight;
var offercontent;
var personaliseLast;
var delid;

var backgrounds = new Array("1","2","3","4","5","6","7","8","9","10");
var personaliseOptions = new Array("partner","family","friends");
var updatedList = new Array();

jQuery(document).ready(function()
{
	initNavigation();
	setScreenWidth(screen.width);
	setScreenHeight(screen.height);
	setRandomBackground();

	window.setTimeout("jQuery('#cboxOverlay').height(jQuery(document).height());", 5000);

	if (typeof hasAccordion != 'undefined')
	{
		initAccordionMenu();
	}
	else if (typeof hasDetailSliders != 'undefined')
	{
		initDetailSliders();

		if (typeof travellingPreference != 'undefined')
		{
			travellingPreference = parseInt(travellingPreference);
			if (travellingPreference >= 1 && travellingPreference <= 3)
			{
				travID = personaliseOptions[travellingPreference - 1];
				jQuery("#" + travID).toggleClass("custom-selected", true);

				jQuery("#travelling-" + travID).fadeIn("slow");
				personaliseLast = travID;
			}
		}

	}
	else if (typeof hasOfferList != 'undefined')
	{
		initOfferList();
		getFilters();
	}

	jQuery().bind("cbox_open", function()
	{
		//hide drop down lists
		jQuery("select").hide();
	});

	jQuery().bind("cbox_complete", function()
	{
		//make sure the overlay covers the entire page
		jQuery("#cboxOverlay").height(jQuery(document).height());
	});

	jQuery().bind("cbox_cleanup", function()
	{
		//un-hide the drop down lists
		jQuery("select").show();

		//remove the initial actions
		jQuery.cookie("initialAction", null);
		jQuery.cookie("initialActionParameter1", null);
	});

	jQuery().bind("cbox_closed", function()
	{
		if (offerListActive())
		{
			resumeOfferList();
		}
	});

	//check if we need to do anything first thing
	var initialAction = jQuery.cookie("initialAction");
	var initialActionParameter1 = jQuery.cookie("initialActionParameter1");
	jQuery.cookie("initialAction", null);
	jQuery.cookie("initialActionParameter1", null);
	if (initialAction == "login")
	{
		loginPopup();
	}
	else if (initialAction == "loginSurprise")
	{
		loginPopupSurprise();
	}
	else if (initialAction == "goToWishlist")
	{
		if (initialActionParameter1 == "isStaging")
		{
			goToWishlist("/Staging/My_Wishlist");
		}
		else
		{
			goToWishlist("/My_Wishlist");
		}
	}
	else if (initialAction == "addFavourite")
	{
		addFavourite(parseInt(initialActionParameter1));
	}
	else if (initialAction == "deleteFavourite")
	{
		deleteFavourite(parseInt(initialActionParameter1));
	}
});

function initNavigation()
{
	jQuery("#navigation img").mouseover(function()
	{
		var image = '/Skins/Moments/images/buttons/btn_' + jQuery(this).attr('name') + '_on.png';
		jQuery(this).attr('src', image);
	}).mouseout(function()
	{
		var image = '/Skins/Moments/images/buttons/btn_' + jQuery(this).attr('name') + '_off.png';
		jQuery(this).attr('src', image);
	});
}

function initAccordionMenu()
{
	jQuery('#acc-menu ul').hide();
	jQuery('#acc-menu ul:first').show();

	jQuery('#acc-menu li a').click(

		function()
		{
			var checkElement = jQuery(this).next();
			var check = jQuery(this);

			checkElement.slideToggle('normal', toggleArrow);

			function toggleArrow()
			{
				check.toggleClass("selected");
			}
		}
	);
}

function initOfferList()
{
	jQuery('#offerlist .scroller').cycle(
	{
		fx: 'scrollRight',
		speed: 'fast',
		timeout: 12000,
		delay: -2000,
		prev: '#prev',
		next: ' #next',
		//pager: '#s6 .nav',
		before: function()
		{
		}
	});
}

function pauseOfferList()
{
	jQuery('#offerlist .scroller').cycle("pause");
}

function resumeOfferList()
{
	jQuery('#offerlist .scroller').cycle("resume");
}

function getFilters()
{
	flocal = getHTML("local");
	finternational = getHTML("international");
	fall = jQuery(".scroller").html();
}

function initDetailSliders()
{
	//Offer Slider
	jQuery('#detailfeature .scroller').cycle({
		fx: 'fade',
		speed: 1000,
		timeout: 6000,
		pager: '#detailfeature .nav'
	});

	/* Some Styling */
	var imgTotal = jQuery('#detailfeature .scroller img').size();

	//Related Slide
	jQuery('#related-slide .scroller').cycle({
		fx: 'scrollRight',
		speed: 'fast',
		timeout: 0,
		next: '#related-slide .next',
		prev: '#related-slide .prev'
	});

	jQuery(".left-buttons img").mouseover(function()
	{
		var image = '/Skins/Moments/images/titles/stitle_' + jQuery(this).attr('name') + '_on.png';
		jQuery(this).attr('src', image);
	}).mouseout(function()
	{
		var image = '/Skins/Moments/images/titles/stitle_' + jQuery(this).attr('name') + '_off.png';
		jQuery(this).attr('src', image);
	});
}

function setScreenWidth(w)
{
	screenwidth = w;
}
function setScreenHeight(h)
{
	screenheight = h;
}

function getScreenWidth()
{
	if (screenwidth == 1024)
	{
		if (screenheight > 768)
		{
			return 1280;
		}
		else
		{
			return screenwidth;
		}
	}
	else if (screenwidth == 1280)
	{
		if (screenheight > 720)
		{
			return 1440;
		}
		else
		{
			return screenwidth;
		}
	}
	else if (screenwidth == 1680)
	{
		if (screenheight > 1050)
		{
			return 2048;
		}
		else
		{
			return screenwidth;
		}
	}
	else
	{
		return 2048;
	}
}

function setRandomBackground()
{
	ranID = getRandom(backgrounds.length);
	jQuery("body").css("background-image", "url(/Skins/Moments/images/backgrounds/" + getScreenWidth() + "/" + backgrounds[ranID] + ".jpg)");
}

function getRandom(ranMax)
{
	return Math.floor(Math.random() * ranMax);
}

// Actions
function closePopup()
{
	jQuery.fn.colorbox.close();
}

function offerListActive()
{
	return jQuery("*").is(".scroller");
}

function filterBy(type)
{
	jQuery(".scroller").empty();

	if (type == "all")
	{
		jQuery(".scroller").append(fall);
	}
	else
	{
		if (type == "list")
		{
			filterby = updatedList;
		}
		else
		{
			filterby = this["f" + type];
		}
		var htmlobj = "";

		for (i = 0; i < filterby.length; i++)
		{
			htmlobj += "<div id='page" + (i + 1) + "' class='offer-set'>";
			htmlobj += filterby[i];
			htmlobj += "</div>";
			jQuery(".scroller").append(htmlobj);

			htmlobj = "";
		}
	}
	initOfferList();
}

function getHTML(filter)
{
	var filterarr = new Array();
	var filterObj = jQuery("." + filter);
	var htmlobj = "";

	for (i = 0; i < filterObj.length; i++)
	{
		htmlobj += "<div class='offer-item " + filter + "'>";
		htmlobj += jQuery(filterObj[i]).html();
		htmlobj += "</div>";

		if (i == 4 || i == 8 || i == filterObj.length - 1)
		{
			filterarr.push(htmlobj);
			htmlobj = "";
		}
	}
	return filterarr;
}

//@param Pop-up buttons in HTML format
var BUTTONS = (function()
{
	var private = {
		'OK': '<ul><li class="popup"><a href="javascript:void(0);" onclick="closePopup(); return false;">Ok</a></li></ul>',
		'DELETE': '<ul><li class="popup"><a href="javascript:void(0);" onclick="deleteConfirm(delid); return false;">Delete</a></li><li class="popup"><a href="javascript:void(0);" onclick="closePopup(); return false;">Cancel</a></li></ul>',
		'ADDED_FAV': '<img src="/Skins/Moments/images/icons/icon_fav_gry.jpg" width="16" height="16" title="This offer is in your Wishlist!" alt="This offer is in your Wishlist!" />'
	};

	return {
		get: function(name) { return private[name]; }
	};
})();

//@param JSON variables returned by server ajax methods
var OPERATION = (function()
{
	var private = {
		'ADD_SUCCESS': 'Offer Added To Favourites List',
		'ADD_DUPLICATE': 'Offer Was Already In Favourites List',
		'ADD_NOID': 'Offer ID Not Specified',
		'ADD_NA': 'Offer Not Currently Available',
		'ADD_NOLOGIN': 'User Not Logged In',
		'DEL_SUCCESS': 'Offer Removed From Favourites',
		'DEL_NOTINFAV': 'Offer Was Not In Favourites List',
		'DEL_NOID': 'Offer ID Not Specified',
		'DEL_NOLOGIN': 'User Not Logged In',
		'LOGIN_SUCCESS': 'User Logged In',
		'LOGIN_INCORRECT': 'Incorrect Password',
		'LOGIN_NOMEMBER': 'No Such Member',
		'LOGIN_INVALID': 'Invalid Email',
		'FORGOT_SUCCESS': 'Sent',
		'FORGOT_NOMEMBER': 'No Such Member',
		'FORGOT_ALREADY': 'Password Already Sent',
		'FORGOT_INVALID' : 'Invalid Email',
		'TRAVEL_UPDATED': 'User Preferences Updated',
		'TRAVEL_NA': 'Offer Not Currently Available',
		'TRAVEL_NOID': 'Offer ID Not Specified',
		'TRAVEL_INVALID': 'Invalid Travelling Preference',
		'TRAVEL_NOLOGIN': 'User Not Logged In'
	};

	return {
		get: function(name) { return private[name]; }
	};
})();

//@param Pop-up title and body text
var POPUP = (function()
{
	var private = {
		'TITLE_ADDED': 'Added to Wishlist!',
		'TITLE_DELETE': 'Delete from Wishlist',
		'TITLE_DUPLICATE': 'Offer already saved!',
		'TITLE_NOID': 'Error!',
		'TITLE_NA': 'Offer not available!',
		'TITLE_LOGIN_DEFAULT': 'Log in to experience all the benefits of MasterCard Moments!',
		'TITLE_LOGIN_SURPRISE': 'You are not logged in. Please log in to experience all the benefits of MasterCard Moments!',
		'TITLE_PWDSENT': 'Password Sent!',
		'BODY_ADDED': '<p>The offer has been successfully saved to your wishlist.</p>',
		'BODY_DELETE': '<p>Are you sure you want to delete this offer from your wishlist?</p>',
		'BODY_DUPLICATE': '<p>The offer selected has been previously saved to your wishlist.</p><p><a href="/My_Wishlist" style="color: red">View My Wishlist</a><p>',
		'BODY_NOID': '<p>The offer ID has not been identified.</p>',
		'BODY_NA': '<p>This offer is currently not available.</p>',
		'BODY_PWDSENT': '<p>Thank you, your password has been sent to your email address.</p>',
		'BODY_NOTINFAV': '<p>The offer selected is not in the wishlist.</p>'
	};

	return {
		get: function(name) { return private[name]; }
	};
})();

//@param Pop-up title and body text
var VALIDATION = (function()
{
	var private = {
		'ERR_LOGIN_NOMEMBER': 'The username entered does not exist.',
		'ERR_LOGIN_INCORRECT': 'The password entered is invalid.',
		'ERR_LOGIN_INVALID': 'The email entered is invalid.',
		'ERR_FORGOT_NOMEMBER': 'The username entered does not exist.',
		'ERR_FORGOT_ALREADY': 'Your password had already been sent.',
		'ERR_FORGOT_INVALID': 'The email entered is invalid.'
	};

	return {
		get: function(name) { return private[name]; }
	};
})();

function loginPopup()
{
	//check if in https
	if (window.location.protocol != "https:")
	{
		jQuery.cookie("initialAction", "login");
		jQuery.cookie("initialActionParameter1", null);
		reloadWindowOverSSL();
		return;
	}

	openLogin(POPUP.get('TITLE_LOGIN_DEFAULT'));
}

function loginPopupSurprise()
{
	//check if in https
	if (window.location.protocol != "https:")
	{
		jQuery.cookie("initialAction", "loginSurprise");
		jQuery.cookie("initialActionParameter1", null);
		reloadWindowOverSSL();
		return;
	}

	openLogin(POPUP.get('TITLE_LOGIN_SURPRISE'));
}

function isLoggedIn(callback)
{
	jQuery.post("https://" + getAJAXDomain() + "/AJAX_Methods/Is_User_Logged_In", {}, callback, "json");
}

function openLogin(pTitle)
{
	resetFlashMessage("login");
	jQuery("#pop-login #pop-title").html(pTitle);
	jQuery.fn.colorbox({ href: '#pop-login', inline: true, open: true, overlayClose: true, initialWidth: 680, initialHeight: 420 });
}

function openPopup(pTitle, pBody, pButtons)
{
	jQuery("#pop-container h1").html(pTitle);
	jQuery("#pop-container #pop-body").html(pBody);
	jQuery("#pop-container .submit-bar").html(pButtons);

	jQuery.fn.colorbox({ href: '#pop-container', inline: true, open: true, overlayClose: true, initialWidth: 550, initialHeight: 250 });
}

function openForgotPass()
{
	resetFlashMessage("forgot");
	jQuery.fn.colorbox({ href: '#pop-forgot', inline: true, open: true, overlayClose: true, initialWidth: 680, initialHeight: 420 });
}

function goToWishlist(url)
{
	//check if in https
	if (window.location.protocol != "https:")
	{
		jQuery.cookie("initialAction", "goToWishlist");
		jQuery.cookie("initialActionParameter1", url.indexOf("/Staging/My_Wishlist") >= 0 ? "isStaging" : null);
		reloadWindowOverSSL();
		return;
	}

	isLoggedIn(function(data)
	{
		if (data.operationStatus)
		{
			if (url.indexOf("?") > 0)
			{
				window.location = url + "&v" + Math.floor(Math.random() * 100001) + "=1";
			}
			else
			{
				window.location = url + "?v" + Math.floor(Math.random() * 100001) + "=1";
			}
		}
		else
		{
			jQuery.cookie("initialAction", "goToWishlist");
			jQuery.cookie("initialActionParameter1", url.indexOf("/Staging/My_Wishlist") >= 0 ? "isStaging" : null);
			openLogin(POPUP.get('TITLE_LOGIN_SURPRISE'));
		}
	});
}

function addFavourite(id)
{
	//check if in https
	if (window.location.protocol != "https:")
	{
		jQuery.cookie("initialAction", "addFavourite");
		jQuery.cookie("initialActionParameter1", id);
		reloadWindowOverSSL();
		return;
	}
	
	buttontype = BUTTONS.get('OK');
	pauseOfferList();

	jQuery.post("https://" + getAJAXDomain() + "/AJAX_Methods/Add_To_Favourites", { offer_id: id }, function(data)
	{
		response = data.operationStatus;

		//DEBUG
		//response = OPERATION.get('ADD_SUCCESS');

		switch (response)
		{
			case OPERATION.get('ADD_SUCCESS'):
				openPopup(POPUP.get('TITLE_ADDED'), POPUP.get('BODY_ADDED'), buttontype);
				var addToFavouritesLink = jQuery("a.addToFavouritesLinkOffer" + id);
				var removeFromFavouritesLink = jQuery("a.removeFromFavouritesLinkOffer" + id);
				if (removeFromFavouritesLink.size() > 0)
				{
					addToFavouritesLink.hide();
					removeFromFavouritesLink.show();
				}
				else
				{
					addToFavouritesLink.parent().html(BUTTONS.get('ADDED_FAV'));
				}
				break;

			case OPERATION.get('ADD_DUPLICATE'):
				openPopup(POPUP.get('TITLE_DUPLICATE'), POPUP.get('BODY_DUPLICATE'), buttontype);
				break;

			case OPERATION.get('ADD_NOID'):
				openPopup(POPUP.get('TITLE_NOID'), POPUP.get('BODY_NOID'), buttontype);
				break;

			case OPERATION.get('ADD_NA'):
				openPopup(POPUP.get('TITLE_NA'), POPUP.get('BODY_NA'), buttontype);
				break;

			case OPERATION.get('ADD_NOLOGIN'):
				jQuery.cookie("initialAction", "addFavourite");
				jQuery.cookie("initialActionParameter1", id);
				openLogin(POPUP.get('TITLE_LOGIN_SURPRISE'));
				break;
		}
	}, "json");
}

function deleteFavourite(id)
{
	buttontype = BUTTONS.get('DELETE');
	pauseOfferList();

	isLoggedIn(function(data)
	{
		if (data.operationStatus)
		{
			delid = id;
			openPopup(POPUP.get('TITLE_DELETE'), POPUP.get('BODY_DELETE'), buttontype);
		}
		else
		{
			jQuery.cookie("initialAction", "deleteFavourite");
			jQuery.cookie("initialActionParameter1", id);
			openLogin(POPUP.get('TITLE_LOGIN_SURPRISE'));
		}
	});
}

function deleteConfirm(delid)
{
	buttontype = BUTTONS.get('OK');
	jQuery.post("https://" + getAJAXDomain() + "/AJAX_Methods/Remove_From_Favourites", { offer_id: delid }, function(data)
	{
		response = data.operationStatus;

		//DEBUG
		//response = OPERATION.get('DEL_SUCCESS');

		switch (response)
		{
			case OPERATION.get('DEL_SUCCESS'):
				var addToFavouritesLink = jQuery("a.addToFavouritesLinkOffer" + delid);
				var removeFromFavouritesLink = jQuery("a.removeFromFavouritesLinkOffer" + delid);
				if (addToFavouritesLink.size() > 0)
				{
					addToFavouritesLink.show();
					removeFromFavouritesLink.hide();
				}
				else
				{
					removeItem(delid);
					resumeOfferList();
				}
				closePopup();
				break;

			case OPERATION.get('DEL_NOTINFAV'):
				openPopup(POPUP.get('TITLE_NA'), POPUP.get('BODY_NOTINFAV'), buttontype);
				break;

			case OPERATION.get('DEL_NOID'):
				openPopup(POPUP.get('TITLE_NOID'), POPUP.get('BODY_NOID'), buttontype);
				break;

			case OPERATION.get('DEL_NOLOGIN'):
				openLogin(POPUP.get('TITLE_LOGIN_SURPRISE'));
				break;
		}
	}, "json");
}

function removeItem(id)
{
	reloadWindow();
}

function authUser()
{
	usremail = jQuery("#email").val();
	usrpassword = jQuery("#password").val();
	usrremember = jQuery("#remember_me:checked").size() > 0 ? true : false;

	jQuery.post("https://" + getAJAXDomain() + "/AJAX_Methods/Login", { email: usremail, password: usrpassword, remember_me: usrremember }, function(data)
	{
		response = data.operationStatus;

		//DEBUG
		//response = OPERATION.get('LOGIN_SUCCESS');

		switch (response)
		{
			case OPERATION.get('LOGIN_SUCCESS'):
				var initialAction = jQuery.cookie("initialAction");
				var initialActionParameter1 = jQuery.cookie("initialActionParameter1");
				if (initialAction == "goToWishlist")
				{
					jQuery.cookie("initialAction", null);
					jQuery.cookie("initialActionParameter1", null);
					if (initialActionParameter1 == "isStaging")
					{
						goToWishlist("/Staging/My_Wishlist");
					}
					else
					{
						goToWishlist("/My_Wishlist");
					}
				}
				else
				{
					reloadWindow();
				}
				break;

			case OPERATION.get('LOGIN_INCORRECT'):
				flashMessage(VALIDATION.get('ERR_LOGIN_INCORRECT'), "login");
				break;

			case OPERATION.get('LOGIN_NOMEMBER'):
				flashMessage(VALIDATION.get('ERR_LOGIN_NOMEMBER'), "login");
				break;

			case OPERATION.get('LOGIN_INVALID'):
				flashMessage(VALIDATION.get('ERR_LOGIN_INVALID'), "login");
				break;
		}
	}, "json");
}

function reloadWindow()
{
	var url = window.location.toString();
	if (url.indexOf("?") > 0)
	{
		window.location = window.location + "&v" + Math.floor(Math.random() * 100001) + "=1";
	}
	else
	{
		window.location = window.location + "?v" + Math.floor(Math.random() * 100001) + "=1";
	}
}

function reloadWindowOverSSL()
{
	var url = window.location.toString();
	if (url.indexOf("?") > 0)
	{
		window.location = "https:" + window.location.toString().substr(5) + "&v" + Math.floor(Math.random() * 100001) + "=1";
	}
	else
	{
		window.location = "https:" + window.location.toString().substr(5) + "?v" + Math.floor(Math.random() * 100001) + "=1";
	}
}

function sendPassword()
{
	usremail = jQuery("#forgotemail").val();
	buttontype = BUTTONS.get('OK');

	jQuery.post("https://" + getAJAXDomain() + "/AJAX_Methods/Forgot_Password", { email: usremail }, function(data)
	{
		response = data.operationStatus;

		//DEBUG
		//response = OPERATION.get('FORGOT_SUCCESS');

		switch (response)
		{
			case OPERATION.get('FORGOT_SUCCESS'):
				openPopup(POPUP.get('TITLE_PWDSENT'), POPUP.get('BODY_PWDSENT'), buttontype);
				break;

			case OPERATION.get('FORGOT_NOMEMBER'):
				flashMessage(VALIDATION.get('ERR_FORGOT_NOMEMBER'), "forgot");
				break;

			case OPERATION.get('FORGOT_ALREADY'):
				flashMessage(VALIDATION.get('ERR_FORGOT_ALREADY'), "forgot");
				break;

			case OPERATION.get('FORGOT_INVALID'):
				flashMessage(VALIDATION.get('ERR_FORGOT_INVALID'), "forgot");
				break;
		}
	}, "json");
}

function verifyBIN(inputId)
{
	usrbin = jQuery("#" + inputId).val();

	jQuery.post("https://" + getAJAXDomain() + "/AJAX_Methods/Is_BIN_Valid", { bin_number: usrbin }, function(data)
	{
		response = data.operationStatus;

		//DEBUG
		//response = true;

		if (response)
		{
			jQuery("#bin-result").html("Valid!");
			jQuery("#bin-result").css("color", "green");
			jQuery("div.register-section").slideDown("slow");
		}
		else
		{
			jQuery("#bin-result").html("Invalid!");
			jQuery("#bin-result").css("color", "red");
		}
	}, "json");
}

function setPreference(offerid, travelid)
{
	travelid = parseInt(travelid);
	if (travelid >= 1 && travelid <= 3)
	{
		for (i = 0; i < personaliseOptions.length; i++)
		{
			jQuery("#" + personaliseOptions[i]).toggleClass("custom-selected", false);
		}
		jQuery("#" + personaliseOptions[travelid - 1]).toggleClass("custom-selected", true);
		jQuery("#travelling-" + personaliseLast).fadeOut("fast");
		jQuery("#travelling-" + personaliseOptions[travelid - 1]).fadeIn("slow");

		personaliseLast = personaliseOptions[travelid - 1];

		jQuery.post("https://" + getAJAXDomain() + "/AJAX_Methods/Set_User_Preferences", { travels_with: travelid, offer_id: offerid }, function(data)
		{
			response = data.operationStatus;

			//DEBUG
			//response = OPERATION.get('TRAVEL_UPDATED');

			switch (response)
			{
				case OPERATION.get('TRAVEL_UPDATED'):
					break;

				case OPERATION.get('TRAVEL_NA'):
					break;

				case OPERATION.get('TRAVEL_NOID'):
					break;

				case OPERATION.get('TRAVEL_INVALID'):
					break;

				case OPERATION.get('TRAVEL_NOLOGIN'):
					openLogin(POPUP.get('TITLE_LOGIN_SURPRISE'));
					break;
			}
		}, "json");
	}
}

function flashMessage(errmsg, type)
{
	jQuery("#err" + type).html(errmsg);
}

function resetFlashMessage(type)
{
	if (jQuery("*").is("#err" + type))
	{
		jQuery("#err" + type).html("");
	}
}

function getAJAXDomain()
{
	if (document.domain.indexOf(".co.nz") > 0)
	{
		return "www.mastercardmoments.co.nz";
	}
	return "www.mastercardmoments.com.au";
}

function printPage()
{
	window.print();
}
