var sEmailPattern = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)$/i;

// Initialization

$(document).ready(function(){    
	
	// Recent news
	if (recentNews)	{
		setTimeout(switchNews, RNSwitch);
	}

	// Inputs with place holders
	$('.placeholder').each(function(index, el){

		var el = $(el);
		el.blur(placeholderInputBlur);
		el.focus(placeholderInputFocus);
		el.val(el.attr('placeholder'));

		el.parents('form:not(.submit-keep-placeholders)').bind('submit', placeholderFormSubmit);
	});

	// Categories menu
	$('#categoriesmenu > li > a').each(function(index, el){

		var el = $(el);
		if (el.siblings('ul').length > 0){
			el.click(categorymenuOpen);
		}
	});

	// Google maps
	if ($('.googlemaps').length) {
		loadGoogleMapsScript('loadMap');
	}
});
 
 
/* Placeholders */

function placeholderInputFocus(event){

   var el = $(event.target);

   if (el.hasClass('placeholder')){
      el.val('');
      el.removeClass('placeholder');
   }
}

function placeholderInputBlur(event){

   var el = $(event.target);

   if (!el.hasClass('placeholder') && el.val().replace(/(^[\s\xA0]+|[\s\xA0]+$)/g, '') == ''){
      el.val(el.attr('placeholder'));
      el.addClass('placeholder');
   }
}

function placeholderFormSubmit(event){

   var form = $(event.target);
   
   form.find('input.placeholder').each(function(index, el){
      placeholderInputFocus({'target': $(el)});
   });

   return true;
}

function placeholderFormSubmitCancel(form){

   var form = $(form);
      
   form.find('input.placeholder').each(function(index, el){
      placeholderInputBlur({'target': $(el)});
   });

   return true;
}

/* Categories */

function categorymenuOpen(event){
	
	var el = $(event.target).parent();
		
	if (!el.hasClass('active')) {
		
		el.children('ul').slideDown();
		el.siblings('.active').removeClass('active').children('ul').slideUp();		
		el.addClass('active');
	}
	
	return false;
}



/* Common functions */

function updateElement(oElement, sUrl) {
    
    oElement.attr('disabled', 'disabled');

    $.get(sUrl, {},
        function(sResponse){
            oElement.html(sResponse);
            oElement.removeAttr('disabled');
        }
    );
}
            
function isPositiveInt(sString){
    
    if (typeof sString != 'string'){
        return (sString > 0);
    }
    
    var iString = parseInt(sString);
    
    if (isNaN(iString)){
        return false;
    }
    
    return (iString > 0); 
}

function checkAdressesForm(eForm) {
    
    if (!isPositiveInt($(eForm).find("input[name=billing_address_id]:checked").val())){
        alert('Please select billing address');
        return false;
    }
    
    if (!isPositiveInt($(eForm).find("input[name=shipping_address_id]:checked").val())){
        alert('Please select shipping address');
        return false;
    }
    
    return true;
}

function slideToggle(el, bShow){
    var $el = $(el), height = $el.data("originalHeight"), visible = $el.is(":visible");

    // if the bShow isn't present, get the current visibility and reverse it
    if( arguments.length == 1 ) bShow = !visible;

    // if the current visiblilty is the same as the requested state, cancel
    if( bShow == visible ) return false;

    // get the original height
    if( !height ){
        // get original height
        height = $el.show().height();
        // update the height
        $el.data("originalHeight", height);
        // if the element was hidden, hide it again
        if( !visible ) $el.hide().css({height: 0});
    }

    // expand the knowledge (instead of slideDown/Up, use custom animation which applies fix)
    if( bShow ){
        $el.show().animate({height: height}, {duration: 250});
    } else {
        $el.animate({height: 0}, {duration: 250, complete:function (){
                $el.hide();
            }
        });
    }
}

function paymentShowProperFields(sCardType){
    
    if (sCardType == 'VISA' || sCardType == 'MC' || sCardType == 'AMEX') {
        slideToggle('#pay_cvn_container', true);
    }
    else {
        slideToggle('#pay_cvn_container', false);
        $('#pay_cvn').val('');
    }
    
    if (sCardType == 'SWITCH') {
        slideToggle('#pay_issueno_container', true);
    }
    else {
        slideToggle('#pay_issueno_container', false);
        $('#pay_issueno').val('');
    }
}

function productUpdatePrice(eOption) {
	$('#product_price').text($(eOption).attr('price'));
}

/* Store locator */

function initializeStoreLocator(){
	
	var initialLatLng = new google.maps.LatLng(53.42323775431845, -7.795331054687491);
	
	var mapOptions = {
		zoom: 7,
		center: initialLatLng,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		scrollwheel: false
	};
	
	map = new google.maps.Map(document.getElementById("store-locator-google-map"), mapOptions);	
	
	$('#location_area').change(storeLocatorAreaChanged)
}

function storeLocatorAreaChanged(event) {
	
	var eSelect = $(event.target);
	var iAreaId = eSelect.val();	
	
	for (i in markers){
		markers[i].setMap(null); 
		google.maps.event.clearListeners(markers[i], 'click');
		infowindows[i].close();
	}                         
	markers.length = 0;
	infowindows.length = 0;
	
	if (iAreaId != 0) {
		
		eSelect.attr('disabled', 'disabled');
		
		$.get(sControllerUrl + 'get-locations/area_id/' + iAreaId, {}, function(aData){
			
				if (aData.length > 0){
					
					var latLngBounds = new google.maps.LatLngBounds();
					
					storeLocatorSetInfoHTML('');
					
					for (i in aData){
						
						var latLng = new google.maps.LatLng(aData[i].lat, aData[i].lng);
						latLngBounds.extend(latLng);
						
						markers[i] = new google.maps.Marker({
							position: latLng,
							map: map,
							title: aData[i].name
						});
						
						infowindows[i] = new google.maps.InfoWindow({
							content: '<strong>' + aData[i].name + '</strong><div>' + aData[i].address.replace(/(\n)/g, "<br>") +  '</div>'
						});
						
						storeLocatorAttachInfowindow(markers[i], infowindows[i]);						
						storeLocatorAddAddress(aData[i], i);
					}
					
					map.fitBounds(latLngBounds);
					
					if (map.getZoom() > 9){
						map.setZoom(9);
					}

				}
				else {
					
					storeLocatorSetInfoHTML('<p>No stores found in the county.</p>');
				}
				
				eSelect.attr('disabled', '');
			},
			'json'
		)
	}
	else {
		storeLocatorSetInfoHTML('');
	}
}

function storeLocatorAttachInfowindow(marker, infowindow) {
	
	google.maps.event.addListener(marker, 'click', function() {
		
		for (i in infowindows){
			infowindows[i].close();
		}
		
		infowindow.open(map, marker);
	});
}

function storeLocatorSetInfoHTML(content){
	$('#store-locator .info').html(content);
}

function storeLocatorAddAddress(aItem, i){
	
	var container = $('#store-locator .info');
	
	var storeElement = $('<div>');	
	storeElement.append($('<h5>').html(aItem.name));
	storeElement.append($('<p>').html(aItem.address.replace(/(\n)/g, "<br>")));
	
	storeElement.addClass('store');
	if (i % 3 == 0) {
		storeElement.addClass('newline');
	}
	
	storeElement.appendTo(container);
	storeElement.click(function(){
		google.maps.event.trigger(markers[i], 'click');
	});
}


/* Map */

function loadMap() {
	
	$('.googlemaps').each(function(index, el){
				
		var map = new GMap2(el);            
		
		var container = $(el).parent();
		var center = new GLatLng(container.attr('lat'), container.attr('lng'));
		map.setUIToDefault();      		
		map.setCenter(center);
		map.setZoom(parseInt(container.attr('zoom')));
		map.addOverlay(new GMarker(center));
	});
}

function loadGoogleMapsScript(callback) {
	var script = document.createElement("script");
	script.type = "text/javascript"; 	
	script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=" + callback;
	document.body.appendChild(script);
}                            


// Recent Newss

var RNFadeout = 180;
var RNSlide = 300;
var RNSwitch = 10000;

function updateRecentNewsContent(){
    var item = recentNews[recentNewsIndex];
    $('#newsbar .contentswrapper .contents').html('<span class="date">' + item.date + '</span> | <a href="' + sBaseUrl + 'news/view/id/' + item.id + '">' + item.content + '</a>');
}

function switchNews() {

    if (recentNewsIndex < recentNews.length-1){
        recentNewsIndex += 1;
    }
    else {
        recentNewsIndex = 0;
    }

    var block = $('#newsbar .contentswrapper .contents');
    
    block.fadeOut(RNFadeout, function(){    
        updateRecentNewsContent();
        $(this).css({
            marginLeft: '550px'
            
        }).show().animate({
            marginLeft: '0px'
            
        }, RNSlide);
    });
    
    setTimeout(switchNews, RNFadeout + RNSlide + RNSwitch);
}

/* Product Details */

function productSetActiveImage(i, el) {
	
	el = $(el);
	if (!el.hasClass('active')) {
		
		image_active = i;     		
		
		el.siblings('.active').removeClass('active');		
		el.addClass('active');
		
		$('#medium-image').attr('src', el.children('img').attr('src'));
	}    
}

/* Account block update */

function updateAccountBlock() {
	
	$.get(sBaseUrl + 'ajax/block-account/', {}, function(sResponse) {
			$('#account').html(sResponse);
		},
		'html'
	);
}

/* Check Popup Form */

function checkPopupForm(eForm) {
	
	var sAlert = '';
	var aFields = $(eForm).find('.required').each(function(index, el){

		var aField = $(el);
		
		if (aField.val() == aField.attr('placeholder') ||
			(!aField.is('select') && aField.val().replace(/(^[\s\xA0]+|[\s\xA0]+$)/g, '') == '')){
				
			sAlert = sAlert + '\n - ' + aField.attr('placeholder').replace(/\*/g, '');
		}
	});
	
	var eEmail = $(eForm).find('input[name=email].required');
	if (eEmail && !sEmailPattern.test(eEmail.val())){
		sAlert = sAlert + '\nE-mail address must be valid.';
	}
	
	if (sAlert != '') {		
		alert('Please fullfill following fields:' + sAlert);		
		return false;
	}
	else {
		placeholderFormSubmit({'target': eForm});
		return true;
	}
}