var frontPagePageImageWidth = 0;
var frontPagePageImageHeight = 0;

$(document).ready(function() {
	
	$('a#forgotPassword').click(function() { 
		$('.memberLogin').hide();
		$('.memberResetPassword').show();
		return false;
	});

	if($('.redBtnDisabled').length) {
		$('.redBtnDisabled').click(function(e) {
			e.preventDefault();
		}).css({
			cursor: 'default'
		});
	}

	$('a#returnToLogin').click(function() { 
		$('.memberLogin').show();
		$('.memberResetPassword').hide();
		return false;
	});	
	
	$('a.popupLink').bind('click', function(e) {
		popupWindow($(this).attr('href'), $(this).attr('title'),'width=720, height=500, scrollbars');
		e.preventDefault();
	});
	
	$('form.location-form select#regionId').change(function() {
		$(this).parents('form.location-form').submit();
	});

	$('form.location-form select#countryId').change(function() {
		$('form.location-form select#regionId option').removeAttr('selected');
		$(this).parents('form.location-form').submit();
	});
	
	$('div.alphabet a').click(function() {
		$('input.filterByLetter').val($(this).text()).parents('form.location-form').submit();
		return false;
	});
	
	$('.emailSubscribeInput, .headerSearchInput, .stockNotifyInput').focus(function() {
		$(this).select();
	});
	
	// Init the homepage roatation 
	if ($('#blockHomeRotator').length) {
		var $blockHomeRotator = $('#blockHomeRotator'),
		nav= '.blockHome #blockHomeRotatorNav',
		$navLinks;
		$blockHomeRotator 
		.cycle({ 
			timeout: 7000, 
			speed:  2000,
			pager:  nav,
			fx:     'fade'
		});
		
		
		//show the pager after n seconds
		setTimeout(function() {
			//get the page links
			$navLinks = $(nav).find('a').text('');
			//set the width to center the pager
			$(nav).css('width', (15 * $navLinks.length));
			$(nav).fadeIn('slow', function() {
				$(this).show();
			});
			$navLinks.click(function() { 
				$blockHomeRotator.cycle('pause'); 
			});
		}, 2000);
	}
	
	bVersion = getInternetExplorerVersion();
	
	updateCartHeader();
	updateMemberWelcome();
    
	$('#productOutOfStock form').submit(function() {
		var formData = $(this).serialize();
		$('#stockNotifyMessages').hide();
		$.get('index.php?do=restProductOutOfStock', formData, function(data, textStatus) {
			if ($('response', data).attr('status') != "ok") {
				$('#stockNotifyErrors').show().empty().html($('error-message', data).text());
			}
			else {
				$('.stockNotify').hide();
				$('#stockNotifySuccess').show();
			}
		});
		return false;
	});

	$('form.add-form').submit(function() {
		var form = $(this);
		var formData = form.serialize();
		var formUrl = form.attr('action') + '?rest=true';
		var baseTags = document.getElementsByTagName('base');

		$.ajax({
			url: formUrl,
			data: formData,
			success: function() {
				form.siblings('.added').show();
				updateCartHeader();
			},
			error: function() {
				form.siblings('.error').show();
			}
		});
		return false;
	});
    
	/*$('.subscribe form').submit(function() {
        var form = $(this);
        var formData = form.serialize();
        var formUrl = form.attr('action');
        $.get(formUrl, formData, function(data, textStatus) {
            if ($('response', data).attr('status') != "ok") {
                $('#restSubscribeFormErrors').show().empty().html($('error-message', data).text());
            }
            else {
                window.location = $('response', data).attr('success-node');
            }
        });
        return false;
    });*/

	$('input.defaultSwapText').focus(defaultSwapTextClearCheck).blur(defaultSwapTextReplaceCheck).blur();
    
	/*var totalHeight = 65+243+$('body').height()+20;*/
	$('.popupOverlay').css({
		display: 'none'
	});
	$('.popupContainer').css({
		display: 'none'
	});
	/*$('.popupOverlay').css({'height' : totalHeight});
	$('.popupContainer').css({'height' : totalHeight});*/
    
	$('.issuLink').click(function(e) {
		e.preventDefault();
		if(bVersion == 6) {
			showOverlayIE();
		} else {
			showOverlay();
			if(navigator.platform == 'Win32' || navigator.platform == 'Win64') {
				var str=navigator.userAgent;
				var pattern=/chrome/mi;
				if(str.match(pattern) != null) {
					$('.sIFR-replaced').css({
						'display' : 'none'
					});
				}
			}
		}
	});
    
	$('.popupClose').click(function(e) {
		closeOverlay();
	});
    
	frontPagePageImageWidth = $('.sourceWidth').html();
	frontPagePageImageHeight = $('.sourceHeight').html();
    
	if($('#frontPageImage img').height() == 0 || $('#frontPageImage img').width() == 0) {
		setTimeout('frontpage_image_resize()',1000);
	} else {
		frontpage_image_resize();
	}
	$(window).resize(frontpage_image_resize);
    
	if($('#homeSidebar').length > 0) {
		$('#homeSidebar a').each(function() {
			if($(this).attr('title') == 'morCatalogueLink') {
				$(this).click(function(e) {
					e.preventDefault();
					if(bVersion == 6) {
						showOverlayIE();
					} else {
						showOverlay();
					}
				});
			}
		});
	}
    
});

function showOverlay() {
	if(bVersion == 7) {
		$('.sIFR-replaced').css({
			position: 'relative',
			top: '-9999px'
		});
	}
	$('.popupOverlay').css({
		display: 'block'
	});
	$('.popupContainer').css({
		display: 'block'
	});
	$('.popupOverlay').animate({
		opacity: 0.3
	}, 300, "swing", function() {
		$('.popupContainer').animate({
			opacity: 1.0
		}, 300, "swing");
	});
}

function showOverlayIE() {
	$('.sIFR-replaced').css({
		position: 'relative',
		top: '-9999px'
	});
	//alert(frontPagePageImageHeight);                
	frontPagePageImageHeight = $(window).height();
	$('.popupOverlay').css({
		display: 'block',
		height: frontPagePageImageHeight+'px'
		});
	$('.popupContainer').css({
		display: 'block',
		height: frontPagePageImageHeight+'px'
		});
	$('body').css({
		overflow: 'hidden'
	});
	$('.popupOverlay').animate({
		opacity: 0.3
	}, 300, "swing", function() {
		$('.popupContainer').animate({
			opacity: 1.0
		}, 300, "swing");
	});
}

function closeOverlay() {
	if(bVersion == 6 || bVersion == 7) {
		$('.sIFR-replaced').css({
			position: 'relative',
			top: '0px'
		});
		if(bVersion == 6) {
			$('body').css({
				overflow: 'visible'
			});
		}
	}
	$('.popupContainer').animate({
		opacity: 0.0
	}, 100, "swing", function() {
		$('.popupOverlay').animate({
			opacity: 0.0
		}, 100, "swing", function() {
			$('.popupOverlay').css({
				display: 'none'
			});
			$('.popupContainer').css({
				display: 'none'
			});
			if(navigator.platform == 'Win32' || navigator.platform == 'Win64') {
				var str=navigator.userAgent;
				var pattern=/chrome/mi;
				if(str.match(pattern) != null) {
					$('.sIFR-replaced').css({
						'display' : 'block'
					});
				}
			}
		});
	});		    
}

function defaultSwapTextClearCheck() {
	if ($(this).val() == $(this).attr('title')) {
		$(this).val('');
	}
}
function defaultSwapTextReplaceCheck() {
	if ($(this).val() == '') {
		$(this).val($(this).attr('title'));
	}
}

function popupWindow(url, name, attributes){
	// Append popup to the URL if it does not already exist
	var queryStringExists = false;
	if(url.match(/\?/)) {
		queryStringExists = true;
	}
	
	if(queryStringExists) {
		// Only append if we haven't already got the parameter popup defined
		if(!url.match(/(\?|&)popup=/)) {
			url = url + '&popup=true';
		}
	} else {
		url = url + '?popup=true';
	}
	
	var newWindow = window.open(url, name.replace(/[^A-z]/ig, ''), attributes);
	newWindow.focus();
}

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 updateCartHeader() {
	var totalCartProducts = ""+parseInt(readCookie('totalCartProducts'));
	if(totalCartProducts == '' || totalCartProducts == 'null') {
		totalCartProducts = 0;	
	}
	$('#headerCartCount').html(totalCartProducts);
	
	$('#headerMemberWelcome').html()
}

function updateMemberWelcome() {
	var memberGivenName = ''+readCookie('memberGivenName');
	memberGivenName = decodeURIComponent(memberGivenName.replace(/\+/g, ' '));
	//memberGivenName = memberGivenName.replace(/[^A-Z]/i, '');
	if (memberGivenName == '' || memberGivenName == 'null') {
		memberGivenName = 'Guest';
		$('#headerLogoutLink').hide();
		$('#headerLoginLink').show();
	} else {
		$('#headerMemberGivenName').html(memberGivenName);
		$('#headerLogoutLink').show();
		$('#headerLoginLink').hide();
	}
}

function getInternetExplorerVersion() {
	var rv = -1;
	if (navigator.appName == 'Microsoft Internet Explorer') {
		var ua = navigator.userAgent;
		var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
		if (re.exec(ua) != null)
			rv = parseFloat( RegExp.$1 );
	}
	return rv;
}

function frontpage_image_resize() {
	
	var frontpage_image = $("#frontPageImage img");
	
	var w = frontpage_image.attr("width");
	var h = frontpage_image.attr("height");
	var r = w/h;
	
	var window_w = $(window).width();
	if($(window).height() < $('#wrapper').height()) {
		var window_h = $('#wrapper').height();
		$('#frontPageImage').height(window_h);
	} else {
		var window_h = $(window).height();
		$('#frontPageImage').height('100%');
	}
	var window_r = window_w/window_h;
	
	var new_w;
	var new_h;
	if (window_r >= r) {
		new_w = window_w;
		new_h = window_w/r;
	} else {
		new_w = window_h*r;
		new_h = window_h;
	}
	frontpage_image.attr("width", new_w);
	frontpage_image.attr("height", new_h);
    
	if(window_w < new_w) {
		offset = (new_w - window_w) / 2;
		$("#frontPageImage img").css({
			'margin-left': '-'+offset+'px'
			});
	} else {
		$("#frontPageImage img").css({
			'margin-left': '0px'
		});
	}
    	
}


