/*
 *	__GamersGate_Site_Controllers__
 *	Requires Prototype framework and Script.aculo.us Effects library
 *	Author: Johan Lingvall
 */
 
var giftcards = {
	gc_id : "0",
	gc_code : "0",
	saveAndPreview : function(frm) {
		giftcards.gc_id = $F(frm['id']);
		giftcards.gc_code = $F(frm['code']);
		frm['send'].value = "0";
		$(frm).request({
			onComplete: function(){ giftcards.popUp() }
		})
	},
	saveAndSend : function(frm) {
		frm['send'].value = "1";
		$(frm).submit();
	},
	popUp : function() {
		var url = "/giftcard/" + giftcards.gc_code + "?email_version=";
		var day = new Date();
		var id = day.getTime();
		
		eval("gc" + id + " = window.open(url, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=1,menubar=0,resizable=1,width=600,height=580,left = 50,top = 50');");
	}
 }
 
 var rating = {
	div : "",
	activate : function(el,par) {
		rating.div = $(el);
		var objLeft = findPosX(par);
		var objTop = findPosY(par);
		rating.div.setStyle({position: 'absolute', left: objLeft+"px", top: objTop+"px", display: 'block'});
	},
	over : function (score) {
		var children = rating.div.childElements();
		for (var i=0; i<5; i++) {	
			if (i<score)
				children[i].className = "";
			else
				children[i].className = "hidden";
		}
	},
	inactivate : function(el) {
		var div = $(el);
		div.setStyle({display: 'none'});
	},
	vote : function(sku,score) {
		var url = "/rateProduct?sku=" + sku + "&score=" + score;
		new Ajax.Request(url, 
			{ 
				method: 'get',
				onSuccess: function(req) {
					if (req.responseText != "1") {
						alert(req.responseText);
					}
				}
			});
		return false;
	}
 }
 
 var registration = {
	valid : new Array(),
	validate : function(el) {

		// E-mail
		if (!el || el.id == "reg_email") {
			var email = $F("reg_email");
			if (registration.emailValid(email)) {
				registration.valid["reg_email"] = true;
			} else {
				registration.valid["reg_email"] = false;
			}
		}
		
		// Password
		if (!el || el.id == "reg_password" || el.id == "reg_password2") {
			var pswd1 = $F("reg_password");
			var pswd2 = $F("reg_password2");
			registration.valid["reg_password"] = true;
			registration.valid["reg_password2"] = true;
			if (pswd1.length < 5) {
				registration.valid["reg_password"] = false;
				registration.valid["reg_password2"] = false;
			} 
			if (pswd1 != pswd2) {
				registration.valid["reg_password"] = true;
				registration.valid["reg_password2"] = false;
			}
		}
		
		// Username
		if (!el || el.id == "reg_username") {
			var un = $F("reg_username");
			if (un.length < 3) {
				registration.valid["reg_username"] = false;
				registration.setNotifications();
			} else {
				var url = "/ajaxdata/validation/usernameExists?un=" + un;
				new Ajax.Request(url, 
				{ 
					method: 'get',
					onSuccess: function(req) {
						if (req.responseText == "1") {
							registration.valid["reg_username"] = false;
						} else {
							registration.valid["reg_username"] = true;
						}
						registration.setNotifications();
					}
				});
			}
		} else {
			registration.setNotifications();
		}
	},
	validateAll : function() {
		registration.validate();
		var formValid = true;
		var errorMessage = "";
		for (el in registration.valid) {
			if (!registration.valid[el]) {
				if (el == "reg_email") errorMessage += "The e-mail adress you entered is not valid\n";
				else if (el == "reg_password") errorMessage += "Your password is too short\n";
				else if (el == "reg_password2") errorMessage += "Your repeated password did not match\n";
				else if (el == "reg_username") errorMessage += "Your entered username is already in use\n";
				formValid = false;
			}
		}
		
		if (formValid) {
			return true;
		} else {
			if (errorMessage=="") errorMessage = "One or more fields are not valid";
			alert(errorMessage);
			return false;
		}
	},
	setNotifications : function() {
		for (el in registration.valid) {
			if (registration.valid[el] && $(el)) {
				if ($(el).hasClassName("invalid")) {
					$(el).removeClassName("invalid");
				}
			} else if ($(el)) {
				if (!$(el).hasClassName("invalid")) {
					$(el).addClassName("invalid");
				}
			}
		}
	},
	emailValid : function(email) {
		var pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
		return pattern.test(email);
	}
 }


 
var productList = {
	tempId : 0,
	expandCompact : function(product_id, source) {
		if (source == "") source = "productListCompactExpanded";
		productList.tempId = product_id;
		var url = "/ajaxdata/layout/" + source + "?product_id=" + product_id;
		new Ajax.Request(url, 
		{ 
			method: 'get',
			onSuccess: function(req) {
				var response = req.responseText;
				var expanded_div = $('product_' + productList.tempId + '_expanded');
				expanded_div.update(response);
				$('product_' + productList.tempId + '_minimized').hide();
				var imgcontainer = expanded_div.getElementsByClassName("boxShadow")[0];
				$(imgcontainer).setStyle({opacity: 0});
				Effect.BlindDown(expanded_div, { 
					duration: 0.3, 
					scaleFrom: 30, 
					afterFinish: function() {
						var imgcontainer = $('product_' + productList.tempId + '_expanded').getElementsByClassName("boxShadow")[0];
						new Effect.Opacity(imgcontainer, { from: 0, to: 1, duration: 0.1});
					}
				});
			}
		});
		return false;
	},
	minimize : function(product_id) {
		productList.tempId = product_id;
		var expanded_div = $('product_' + productList.tempId + '_expanded');
		var imgcontainer = expanded_div.getElementsByClassName("boxShadow")[0];
		$(imgcontainer).setStyle({opacity: 0});
		Effect.BlindUp(expanded_div, 
			{ 
				duration: 0.2, 
				scaleTo: 30, 
				afterFinish: function() {
					$('product_' + productList.tempId + '_minimized').show();
				}
			});
	}
}

var topmenu = {
	t : 0,
	open : function(id) {
		
		clearTimeout(topmenu.t);
		var button_id = "topmenu_button_" + id;
		var submenu_id = "topmenu_submenu_" + id;
		var submenu = $(submenu_id);
		
		if (submenu.getStyle("display") == "none") {
			var objLeft = findPosX($(button_id))-2;
			var objTop = findPosY($(button_id))+38;
			submenu.setStyle({position: 'absolute', left: objLeft+"px", top: objTop+"px"});
			topmenu.t = setTimeout('topmenu.submenu_show("' + submenu_id + '")',200);
		}
	},
	close : function(id,e) {
		clearTimeout(topmenu.t);
		
		if (!e) var e = window.event;
		var relTarg = e.relatedTarget || e.toElement;
		
		if (!relTarg) return;
		
		var button_id = "topmenu_button_" + id;
		var submenu_id = "topmenu_submenu_" + id;
		
		if (!$(relTarg).descendantOf(button_id)) {
			var t = setTimeout('topmenu.submenu_hide("' + submenu_id + '")',50);
		}
	},
	submenu_show : function(ref) {
		$(ref).style.display = "block";
	},
	submenu_hide : function(ref) {
		$(ref).style.display = "none";
	}
}

var leftmenu = {
	toggle : function(el) {
		if ($(el).getStyle("display") == "none") {
			new Effect.BlindDown(el , { duration: 0.3 });
		} else {
			new Effect.BlindUp(el , { duration: 0.3 });
		}
		return false;
	},
	open : function(el) {
		if ($(el).getStyle("display") == "none") {
			new Effect.BlindDown(el , { duration: 0.3 });
		}
		return false;
	},
	close : function(el) {
		if ($(el).getStyle("display") == "block") {
			new Effect.BlindUp(el , { duration: 0.3 });
		}
		return false;
	}
}

var profilePublic = {
	clickPublic : function(frm) {
		if (frm["privacy_profilepublic"].checked) {
			// frm["privacy_olstatus"].disabled = false;
			frm["privacy_mygames"].disabled = false;
			frm["privacy_wishlist"].disabled = false;
		} else {
			//frm["privacy_olstatus"].disabled = true;
			//frm["privacy_olstatus"].checked = false;
			frm["privacy_mygames"].disabled = true;
			frm["privacy_mygames"].checked = false;
			frm["privacy_wishlist"].disabled = true;
			frm["privacy_wishlist"].checked = false;
		}
	}
}

var privateMessages = {
	tempId : 0,
	togglePreview : function(id) {
		privateMessages.tempId = id;
		var container = $('messagePreview' + privateMessages.tempId);
		if (container.empty()) {
			var url = "/ajaxdata/layout/privateMessagesPreview?thread_id=" + id;
			new Ajax.Request(url, 
			{
				method: 'get',
				onSuccess: function(req) {
					
					var response = req.responseText;
					$('messagePreview' + privateMessages.tempId).update(response);
					
					privateMessages.open();
					
				}
			});
		} else if (container.style.display == "none") {
			privateMessages.open();
		} else {
			privateMessages.close();
		}
	},
	togglePreviewTutor : function(id) {
		privateMessages.tempId = id;
		var container = $('messagePreview' + privateMessages.tempId);
		if (container.empty()) {
			var url = "/ajaxdata/layout/tutorMessagesPreview?thread_id=" + id;
			new Ajax.Request(url, 
			{
				method: 'get',
				onSuccess: function(req) {
					var response = req.responseText;
					$('messagePreview' + privateMessages.tempId).update(response);
					privateMessages.open();
				}
			});
		} else if (container.style.display == "none") {
			privateMessages.open();
		} else {
			privateMessages.close();
		}
	},
	open : function() {
		if ($('pmTitle' + privateMessages.tempId) && $('pmTitle' + privateMessages.tempId).hasClassName('bold')) {
            $('pmTitle' + privateMessages.tempId).removeClassName("bold");
		}
        if ($('pmIconShowhide' + privateMessages.tempId)) {
            $('pmIconShowhide' + privateMessages.tempId).className = "pmHide";
        }
		Effect.BlindDown('messagePreview' + privateMessages.tempId , { duration: 0.3 });
	}, 
	close : function() {
		$('pmIconShowhide' + privateMessages.tempId).className = "pmShow";
		Effect.BlindUp('messagePreview' + privateMessages.tempId , { duration: 0.3 });
	}
}

var wishlist = {
	removeItem : function(itemId) {
		var url = "/account/wishlist?removeItem=" + itemId;
		new Ajax.Request(url, 
		{
			method: 'get',
			onSuccess: function(req) {
				$("product_" + req.responseText + "_minimized").remove();
				$("product_" + req.responseText + "_expanded").remove();
			}
		});
		return false;
	}
}

var shoppingCart = {
	items : [],
	selectedItem : 0,
	notifierTimer : 0,
	addItem : function(sku,gift) {
		var url = "/shop/addtocart?sku=" + sku + "&gift=" + gift;
		new Ajax.Request(url, 
			{
				method: 'get',
				onSuccess: function(req) {
					if (req.responseText == "1") {
						// Item is added
						if (location.href.indexOf("/shop/checkout") > 0) {
							// If we are in the check out page - refresh page
							window.location.href = "/shop/checkout";
						} else {
							// Reload shoppingcart
							shoppingCart.loadItem("%");
							
							clearTimeout(shoppingCart.notifierTimer);
							shoppingCart.showNotifier(shoppingCart.selectedItem);
							
							// scroll to shopping cart
							var view = document.viewport.getScrollOffsets();
							if (view.top > 200) {
								var t = setTimeout('shoppingCart.scrollToCart()', 300);
							}
							
							shoppingCart.notifierTimer = setTimeout('shoppingCart.closeNotifier()', 3000);
						}
					} else {
						alert(req.responseText);
					}
				}
			});
		return false;
	},
	loadItem : function(itemId) {
		var url = "/ajaxdata/shoppingcart/getitem?itemId=" + itemId + "&selectedItem=" + shoppingCart.selectedItem;
		new Ajax.Request(url, 
			{
				method: 'get',
				onSuccess: function(req) {
					shoppingCart.updateView(req.responseText);
					var matches = req.responseText.match('<!--(.*)-->');
					shoppingCart.selectedItem = matches[1];
				}
			});
	},
	removeItem : function(itemId) {
		var url = "/shop/removefromcart?itemId=" + itemId;
		new Ajax.Request(url, 
			{
				method: 'get',
				onSuccess: function(req) {
					if (location.href.indexOf("gamersgate.com/shop/checkout") > 0) {
						window.location.href = "/shop/checkout";
					} else {
						shoppingCart.loadItem("%");
						//shoppingCart.close();
					}
				}
			});
		return false;
	},
	updateView : function(html) {
		el = $("shoppingcart");
		el.update(html);
		shoppingCart.open();
	},
	scrollToCart : function() {
		Effect.ScrollTo("shoppingcart",{offset: -50});
	},
	toggle : function() {
		if ($("shoppingcart").getStyle("display") == "none") {
			Effect.BlindDown('shoppingcart' , { duration: 0.3 });
		} else {
			Effect.BlindUp('shoppingcart' , { duration: 0.3 });
		}
		return false;
	},
	open : function() {
		if ($("shoppingcart").getStyle("display") == "none") {
			Effect.BlindDown('shoppingcart' , { duration: 0.3 });
		}
	},
	close : function() {
		if ($("shoppingcart").getStyle("display") == "block") {
			Effect.BlindUp('shoppingcart' , { duration: 0.3 });
		}
	},
	showNotifier : function(id) {
		html = '';
		html += '<span class="darkgrey">A product has been added to your shopping cart</span>';
		html += '&nbsp;&nbsp;';
		html += '<span class="grey"></span>';
		html += '<a href="/shop/checkout" title="Checkout" class="blue">Checkout</a>';
		html += '<span class="grey"></span>';
		/* 
		if (id) {
			html += '&nbsp;&nbsp;';
			html += '<span class="grey"></span>';
			html += '<a href="/shop/removefromcart?itemId=' + id + '&ref=1" onclick="return shoppingCart.removeItem(' + id + ');" title="Undo" class="blue">Undo</a>';
			html += '<span class="grey"></span>';
		}
		 */
		html += '&nbsp;&nbsp;';
		html += '<span class="grey"></span>';
		html += '<a href="#" onclick="$(\'addItemNotifier\').style.display=\'none\'; return false;" title="Close" class="blue">Close</a>';
		html += '<span class="grey"></span>';
		
		var el = $("addItemNotifier");
		el.update(html);
		
		var leftpos = findPosX($("mainContentMiddle"));
		var leftpos = leftpos - 20;
		el.setStyle({opacity: 0, left: leftpos + "px", display: "block"});
		new Effect.Opacity(el, { from: 0, to: 1, duration: 0.1 });
		
	},
	closeNotifier : function() {
		var el = $("addItemNotifier");
		if (el.getStyle("display") != "none") {
			new Effect.Opacity(el,
			{
				from: 1,
				to: 0,
				duration: 1.0,
				afterFinish: function() { 
					$("addItemNotifier").update(""); 
				} 
			});
		}
        return false;
	}
}

function agreement_popup(id) { 
	var w = 750;
	var h = 650;
	var url = "/agreement?id=" + id;
	window.open(url, "agreement_popup", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width="+w+",height="+h+",top=20,left=20");
}
function confirm_checkout() {
	var agreements = document.getElementsByName("agreement");
	if (agreements) {
		for (var i = 0; i < agreements.length; i++) {
			if (!agreements[i].checked) {
				alert("You must read and accept all License Agreements");
				return false;
			}
		}
	}
	var payment_method = Form.getInputs('checkout','radio','method').find(function(radio) { return radio.checked; });
	if (typeof(payment_method) == "undefined") {
		alert("Please select a payment method");
		return false;
	}
	return true;
}

function showRegisterFields() {
	$("loginFields").update("").hide();
	var url = "/ajaxdata/shoppingcart/getregform";
	new Ajax.Request(url, 
		{
			method: 'get',
			onSuccess: function(req) {
				$("registerAccount").update(req.responseText).show();
			}
		});
	return false;
}

function billinginfoActivate(elname) {
	var input = $(elname);
	var textspan = $(elname + "_text");
	input.removeClassName("hidden").activate();
	//var value = input.value;
	//input.value = "";
	//input.value = value;
	textspan.update("").hide();
	return false;
}

function Banners_click(banner_id,location_id,href) {
	var url = "/banners/register_click?banner_id=" + banner_id + "&location_id=" + location_id;
	new Ajax.Request(url,{method: 'get', onComplete: function() { window.location.href = href }});
	return false;
}

function toggleStdBox(boxId, icon) {
    var el = $(boxId);
    if (el.hasClassName("box_minimized")) { // Open
        Effect.BlindDown(el , { duration: 0.5 });
        el.removeClassName("box_minimized");
        $(icon).removeClassName("icon_minimized");
    } else { // Close
        Effect.BlindUp(el , { duration: 0.5 });
        el.addClassName("box_minimized");
        $(icon).addClassName("icon_minimized");
    }
}

function gamedocs_Popup(doc_type, doc_id) {
    var url = "/gamedocs/" + doc_type + "/" + doc_id;
    eval("var gamedocs" + doc_id + " = window.open('" + url + "', 'gamedocs" + doc_id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=660,height=580,left=50,top=50');");
    return false;
}


var admin_menu_open = false;
var admin_menu_time = null;
function admin_opensubmenu() {
    if ($("admin_submenu").style.display == "none") 
        admin_menu_time = setTimeout("admin_togglesubmenu(1)", 2000);
}
function admin_closesubmenu(e) {
    clearTimeout(admin_menu_time);
    
    if (!e) var e = window.event;
    var relTarg = e.relatedTarget || e.toElement;
    if (!relTarg) return;
    
    if ($("admin_submenu").style.display == "block" && !$(relTarg).descendantOf("admin_submenu_container")) {
        clearTimeout(admin_menu_time);
        var admin_menu_time = setTimeout("admin_togglesubmenu(0)", 100);
    }
}
function admin_togglesubmenu(d) {
    if (d==1) {
        $("admin_submenu").setStyle({display: "block"});
        admin_menu_open = true;
        $("admin_submenu_inner").setStyle({background : "url('/img/white_transparent_20.png')", backgroundRepeat: "repeat", border : "solid 1px #7fB4d0"});
        clearTimeout(admin_menu_time);
        var admin_menu_time = setTimeout("admin_togglesubmenu(0)", 8000);
    } else if (d==0) {
        $("admin_submenu").setStyle({display: "none"});
        admin_menu_open = false;
        $("admin_submenu_inner").setStyle({background : "transparent", border: "none"});
    }
}