function setBuyMode(val)
{
	$.cookie("telstarBuyMode", val, { path: '/' });
}

function alertShadowBox(rootUrl, message)
{
    Shadowbox.open({
        content:    '<div id="alert-msg"><span>' + message + '</span><br /><br /><br /><img src="' + rootUrl +'images/layout/okBtn.png" alt="ok" onclick="Shadowbox.close();" /></div>',
        player:     "html",
        title:      "",
        height:     176,
        width:      443
    });
}

function confirmShadowBox(rootUrl, message, exec)
{
    Shadowbox.open({
        content:    '<div id="alert-msg"><span>' + message + '</span><br /><br /><br /><img src="' + rootUrl +'images/layout/okBtn.png" alt="ok" onclick="' + exec + '; Shadowbox.close();" />&nbsp;<img src="' + rootUrl +'images/layout/cancelBtn.png" alt="cancel" onclick="Shadowbox.close();" /></div>',
        player:     "html",
        title:      "",
        height:     176,
        width:      443
    });
}

function buyShadowBox(rootUrl, productsId, auction, refresh)
{
	auction = auction || 'n';
	refresh = refresh || 'n';
	
	var fbWnd = false;
	
	if (typeof fbTab != 'undefined')
	{
		fbWnd = fbTab;
	}

	if (fbWnd)
	{
	    Shadowbox.open({
	        content:    '<div id="alert-msg"><span>How would you prefer to purchase this product?</span><br /><br />' + 
	        			'<br /><a href="' + rootUrl.replace("https://", "http://") + 'visit-a-retailer.html" target="_blank" onclick="Shadowbox.close();">' + 
	        			'<img src="' + rootUrl +'images/layout/localRetailerBtn.png" alt="Local retailer" border="0" /></a>&nbsp;' + 
	        			'<a href="' + rootUrl.replace("https://", "http://") + 'scripts/fb_order.php?products_id=' + productsId + '" target="_blank" onclick="Shadowbox.close();">' + 
	        			'<img src="' + rootUrl +'images/layout/buyOnlineBtn.png" alt="Buy online" border="0" /></a></div>',
	        player:     "html",
	        title:      "",
	        height:     176,
	        width:      443
	    });
	}
	else
	{
	    Shadowbox.open({
	        content:    '<div id="alert-msg"><span>How would you prefer to purchase this product?</span><br /><br /><br /><img src="' + rootUrl +'images/layout/localRetailerBtn.png" alt="Local retailer" onclick="localRetailerBtn(\'' + rootUrl + '\');" />&nbsp;<img src="' + rootUrl +'images/layout/buyOnlineBtn.png" alt="Buy online" onclick="buyOnlineBtn(\'' + rootUrl + '\', \'' + productsId + '\', \'' + auction + '\', \'' + refresh + '\'); Shadowbox.close();" /></div>',
	        player:     "html",
	        title:      "",
	        height:     176,
	        width:      443
	    });
	}
}

function localRetailerBtn(rootUrl)
{
	//setBuyMode('retailer');
	setTimeout('redirToResellers("' + rootUrl + '");', 1000);
}

function buyOnlineBtn(rootUrl, productsId, auction, refresh)
{
	auction = auction || 'n';
	refresh = refresh || 'n';
	
	//setBuyMode('online');
	
	setTimeout('addProductToOrder2("' + rootUrl + '", "' + productsId + '", "' + auction + '", "' + refresh + '");', 1000);
}

function addProductToWishList(rootUrl, productsId)
{
	$.ajax({
		type: 'POST',
		contentType: "application/x-www-form-urlencoded;charset=utf-8",
		url: rootUrl + 'scripts/wishlist.php',
		cache: false,
		data: { action: 'add',
				products_id: productsId },
		success: function(response) {
			if (response == 'err')
			{
				setTimeout('alertShadowBox("' + rootUrl + '", "Invalid parameters!");', 500);
			}
			else if (response == 'dup')
			{
				setTimeout('alertShadowBox("' + rootUrl + '", "The product is already in your wishlist.");', 500);
			}
			else
			{
				if ($.trim($('#wishListProducts').html()) == 'empty')
				{
					$('#wishListProducts').html(response);
				}
				else
				{
					$('#wishListProducts').append(response);
				}
				
				setTimeout('alertShadowBox("' + rootUrl + '", "The product was added to your wishlist.");', 500);
			}
		}
	});
}

function removeProductFromWishlist(rootUrl, productsId)
{
	confirmShadowBox(rootUrl, 'Are you sure you want to remove this product from your wishlist?', 'removeProductFromWishlist2(\'' + rootUrl + '\', \'' + productsId + '\')');
}

function removeProductFromWishlist2(rootUrl, productsId)
{
	$.ajax({
		type: 'POST',
		contentType: "application/x-www-form-urlencoded;charset=utf-8",
		url: rootUrl + 'scripts/wishlist.php',
		cache: false,
		data: { action: 'remove',
				products_id: productsId },
		success: function(response) {
			if (response == 'err')
			{
				setTimeout('alertShadowBox("' + rootUrl + '", "Invalid parameters!");', 500);
			}
			else if (response == 'empty')
			{
				$('#wishListProducts').html('empty');
				
				setTimeout('alertShadowBox("' + rootUrl + '", "<div style=\'padding: 0 10px; width: 423px;\'>The product has been removed from your wishlist.</div>");', 500);
			}
			else
			{
				$('#wishListProd' + productsId).remove();

				setTimeout('alertShadowBox("' + rootUrl + '", "<div style=\'padding: 0 10px; width: 423px;\'>The product has been removed from your wishlist.</div>");', 500);
			}
		}
	});
}

function addProductToOrder(rootUrl, productsId, auction, refresh)
{
	auction = auction || 'n';
	refresh = refresh || 'n';

	/*var cookieVal = $.cookie("telstarBuyMode");

	if (cookieVal == 'retailer')
	{
		redirToResellers(rootUrl);
	}
	else if (cookieVal == 'online')
	{
		addProductToOrder2(rootUrl, productsId, auction, refresh);
	}
	else
	{*/
		buyShadowBox(rootUrl, productsId, auction, refresh);
	//}
}

function addProductToOrder2(rootUrl, productsId, auction, refresh)
{

	auction = auction || 'n';
	refresh = refresh || 'n';

	$.ajax({
		type: 'POST',
		contentType: "application/x-www-form-urlencoded;charset=utf-8",
		url: rootUrl + 'scripts/order.php',
		cache: false,
		data: { action: 'add',
				products_id: productsId,
				is_auction: auction },
		success: function(response) {
			if (response == 'err')
			{
				setTimeout('alertShadowBox("' + rootUrl + '", "Invalid parameters!");', 500);
			}
			else
			{
				$('#orderProducts').html(response);
				
				setTimeout('alertShadowBox("' + rootUrl + '", "The product was added to your order.");', 500);
			}
			
			if (refresh == 'y')
			{
				location.href = rootUrl + 'Checkout/';
			}
		}
	});
}

function removeProductFromOrder(rootUrl, productsId, refresh)
{
	confirmShadowBox(rootUrl, 'Are you sure you want to remove this product from your order?', 'removeProductFromOrder2(\'' + rootUrl + '\', \'' + productsId + '\', \'' + refresh + '\')');
}

function removeProductFromOrder2(rootUrl, productsId, refresh)
{
	refresh = refresh || 'n';
	
	$.ajax({
		type: 'POST',
		contentType: "application/x-www-form-urlencoded;charset=utf-8",
		url: rootUrl + 'scripts/order.php',
		cache: false,
		data: { action: 'remove',
				products_id: productsId },
		success: function(response) {
			if (response == 'err')
			{
				setTimeout('alertShadowBox("' + rootUrl + '", "Invalid parameters!");', 500);
			}
			else
			{
				$('#orderProducts').html(response);
				
				setTimeout('alertShadowBox("' + rootUrl + '", "The product has been removed from your order.");', 500);
			}
			
			if (refresh == 'y')
			{
				location.reload();
			}
		}
	});
}

function showCities(rootUrl, val)
{
	$("select#towns").html('<option value="-1">- select town -</option>');
	$("select#retailers").html('<option value="-1">- select retailer -</option>');

	$.ajax({
		type: 'POST',
		contentType: "application/x-www-form-urlencoded;charset=utf-8",
		url: rootUrl + 'scripts/retailers.php',
		cache: false,
		data: { action: 'get_cities_list',
				counties_id: val },
		success: function(response) {
			if (response == 'err')
			{
				setTimeout('alertShadowBox("' + rootUrl + '", "Invalid parameters!");', 500);
			}
			else
			{
				$("select#towns").append(response);
			}
		}
	});
}

function showRetailers(rootUrl, val)
{
	$("select#retailers").html('<option value="-1">- select retailer -</option>');
	
	$.ajax({
		type: 'POST',
		contentType: "application/x-www-form-urlencoded;charset=utf-8",
		url: rootUrl + 'scripts/retailers.php',
		cache: false,
		data: { action: 'get_retailers_list',
				cities_id: val },
		success: function(response) {
			if (response == 'err')
			{
				setTimeout('alertShadowBox("' + rootUrl + '", "Invalid parameters!");', 500);
			}
			else
			{
				$("select#retailers").append(response);
			}
		}
	});
}

function retailerDisabler(val)
{
	if (val)
	{
		$('#towns').attr('disabled', 'disabled');
		$('#counties').attr('disabled', 'disabled');
		$('#retailers').attr('disabled', 'disabled');
	}
	else
	{
		$('#towns').removeAttr('disabled');
		$('#counties').removeAttr('disabled');
		$('#retailers').removeAttr('disabled');
	}
}

function shareWishlist(rootUrl, wishlist_uid)
{
	window.open("http://twitter.com/home?status=Don't know what present to get me? Check out the Telstar Watches website to find out everything I've ever wanted. http://www.TelstarWatches.ie",'TwitterShare','height=250px,width=500px');
	
	window.open('https://www.facebook.com/sharer.php?u=' + escape(rootUrl + '?wishlist_uid=' + wishlist_uid + '&rnd=' + new Date().getTime()),'FacebookShare','toolbar=0,status=0,width=600,height=400');
}

function showRetailersFromMap(rootUrl, val)
{
	$("#retailerslist").hide();
	$.ajax({
		type: 'POST',
		contentType: "application/x-www-form-urlencoded;charset=utf-8",
		url: rootUrl + 'scripts/retailersmap.php',
		cache: false,
		data: { action: 'get_retailers_list',
				counties_id: val },
		success: function(response) {
			if (response == 'err')
			{
				setTimeout('alertShadowBox("' + rootUrl + '", "Invalid parameters!");', 500);
			}
			else
			{
				$("#retailerslist").html(response).fadeIn(1000);
			}
		}
	});
}

jQuery.jQueryRandom = 0;
jQuery.extend(jQuery.expr[":"],
{
    random: function(a, i, m, r) {
        if (i == 0) {
            jQuery.jQueryRandom = Math.floor(Math.random() * r.length);
        };
        return i == jQuery.jQueryRandom;
    }
});

function checkEmail(value) {
	var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
	var regex = new RegExp(emailReg);
	if ((regex.test(value)==false) && (value.length!=0))
	{	      
            return false;
	}
	return true;
}

function redirToHome(rootUrl)
{
	location.href = rootUrl;
}

function redirToResellers(rootUrl)
{
	location.href = rootUrl + 'visit-a-retailer.html';
}

function validateCheckout(rootUrl)
{
	var fname = $.trim($("#Fname").val());
	var lname = $.trim($("#Lname").val());
	var address = $.trim($("#address").val());
	var city = $.trim($("#city").val());
	var county = $.trim($("#county").val());
	var email = $.trim($("#email").val());
	
	if ((fname == '') || (lname == '') || (address == '') || (city == '') || (county == '') || (email == '')) {
		alertShadowBox(rootUrl, 'Please complete all the mandatory fields.');
		return false;
	}

	if (($('#select_country1').attr('checked') == false) && ($('#select_country2').attr('checked') == false)) {
		alertShadowBox(rootUrl, 'Please complete all the mandatory fields.');
		return false;
	}

	if ($('#select_country1').attr('checked') == true) { // validate retailer
		if ($('#retailers').val() == -1) {
			alertShadowBox(rootUrl, 'Please select a retailer.');
			return false;
		}
	}

	if ($('#select_country2').attr('checked') == true) { // validate country
		var country = $.trim($("#country").val());
		if ((country == '') || (country.toLowerCase() == 'specify')) {
			alertShadowBox(rootUrl, 'Please complete all the mandatory fields.');
			return false;
		}
	}
	
	if (!checkEmail(email)) {
		alertShadowBox(rootUrl, 'Invalid e-mail address.');
		return false;
	}
	
	// sharing
	
	if ($('#faceb').attr('checked')) {
		window.open('https://www.facebook.com/sharer.php?u=' + escape(rootUrl + '?fb_prod=' + $(".hidProdIds:random").val()),'FacebookShare','toolbar=0,status=0,width=600,height=400');
	}
	
	if ($('#twitt').attr('checked')) {
		window.open('http://twitter.com/home?status=I just purchased a product online from http://www.TelstarWatches.ie. View their vast supply of classy, stylish watches available for him and her.','TwitterShare','height=250px,width=500px');
	}
	
	setTimeout('redirToHome("' + rootUrl + '");', 1000);
	
	return true;
}
