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(){    
	  
	// 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');
	}
	
	// Header menu
	$('#header .menu > li > a').each(function(index, el){

		var el = $(el);
		el.mouseenter(headerMenuMouseEnter);		
		el.mouseleave(headerMenuMouseLeave);		
	});
});
 
 
/* 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;
}

/* Header menu */

function headerMenuMouseEnter(event) {
	
	var el = $(event.target);
	el.stop().animate({
			'color': '#ffffff',
			'paddingTop': '0'
		},
		100,
		'swing'		
	);
}

function headerMenuMouseLeave(event) {
	
	var el = $(event.target);
	el.stop().animate({
			'color': '#ffce98',
			'paddingTop': '7px'
		},
		250,
		'swing'		
	);
}

/* 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 registrationUpdateTraderTip(){

    if ($('#reg_trader').is(':checked')) {
        $('#reg_trader_tip').slideDown();
    }
    else {
        $('#reg_trader_tip').slideUp();
    }
}

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'));
		
		
	var ePriceOld = $('#product_price_old');	
	
	if (ePriceOld) {
		ePriceOld.text($(eOption).attr('priceold'));	
	}
}
       

/* 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);
}                            



/* Product Details */

function tabsInit(el) {
	
	el.find('.tabs > li').each(function(index, li){
		$(li).click(tabsSelect);
	});
}

function tabsSelect(event) {
	
	var el = $(event.target);
	
	if (!el.hasClass('active')) {                   		
		
		el.siblings('.active').removeClass('active');		
		el.addClass('active');
		
		var i = el.prevAll('li').length;
		el.parent().parent().children('div').hide().eq(i).show();
		
	}
}

// Slideshow

var eSlideshow;
var eSlideshowContent;
var eSlideshowImage;
var eSlideshowImageBackground;
var eSlideshowTitle;
var eSlideshowDescription;
var eSlideshowPages;

function slideshowInit(i) {
	 	
	eSlideshow = $('#slideshow');
	
	if (!eSlideshow) {
		return false;
	}
	
	eSlideshow.find('.previous-container > .previous').click(slideshowPrev);
	eSlideshow.find('.next-container > .next').click(slideshowNext);
	
	eSlideshowPages = eSlideshow.find('.content > .slideshow-pages > .page');	
	eSlideshowPages.each(function(index, elPage){
		$(elPage).click(function(){
			slideshowShow(index);
		})
	});
	
	eSlideshowImage = eSlideshow.find('.foreground');	
	eSlideshowImageBackground = eSlideshow.find('.background');	
	eSlideshowTitle = eSlideshow.find('.content > h1 > a');
	eSlideshowDescription = eSlideshow.find('.content > p');
	eSlideshowContent = eSlideshow.find('.content > h1').add(eSlideshowDescription); 
      	
	i = slideshowGetIndex(i);

	iSlideCurrent = i;
	
	for (var j = 0; j < aSlides.length; j++) {
		$.preloadImage(aSlides[j].image);
	}
}

function slideshowGetIndex(i) {
	
	return (i + aSlides.length) % aSlides.length;
}

function slideshowNext(bAuto) {
	slideshowShow(iSlideCurrent+1);
}

function slideshowPrev() {
	slideshowShow(iSlideCurrent-1);
}

function slideshowShow(i) {
	
	i = slideshowGetIndex(i);
	
	if (iSlideCurrent == i) {
		return;
	}
	
	eSlideshowContent.hide();			
	slideshowSetContent(i);
	
	eSlideshowImageBackground.attr('src', aSlides[i].image);
	                         
	eSlideshowImage.stop().fadeOut(500, function() {
		eSlideshowImage.attr('src', aSlides[i].image);
		eSlideshowImage.show();		
	});
	
	setTimeout(function(){
			eSlideshowContent.fadeIn(400);
		},
		400
	);
	
	eSlideshowPages.eq(iSlideCurrent).removeClass('active');
	eSlideshowPages.eq(i).addClass('active');
	
   	iSlideCurrent = i;
}

function slideshowSetContent(i) {
	i = slideshowGetIndex(i);
	eSlideshowTitle.html(aSlides[i].title);
	eSlideshowTitle.attr('href', aSlides[i].url);
	eSlideshowDescription.html(aSlides[i].description);	
}

// Image preload

jQuery.preloadImage = function(src) {
	jQuery("<img>").attr("src", src);
}

jQuery.preloadImages = function() {
	jQuery.each (arguments,function (e) {
		jQuery("<img>").attr("src", this);
	});
}
