$(document).ready(function(){

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

		var el = $(el);
		el.blur(placeholderInputBlur);
		el.focus(placeholderInputFocus);        
		el.blur();

		el.parents('form:not(.submit-keep-placeholders)').bind('submit', placeholderFormSubmit);
	});
	
	// Recent news
	if (typeof(recentNews) !== 'undefined')	{
		setTimeout(switchNews, RNSwitch);
	}
});

// Placeholders

function placeholderInputFocus(event){

	var el = $(event.target);

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

function placeholderInputBlur(event){

	var el = $(event.target);

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

function placeholderFormSubmit(event){

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

	return true;
}

function placeholderFormSubmitCancel(form){

   var form = $(form);

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

   return true;
}

// Trade registration

function registrationUpdateTrade(){

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

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

// Slide show

var eSlideshow;
var eSlideshowImageBackground;
var eSlideshowImageForeground;
var eSlideshowContent;
var eSlideshowTitle;
var eSlideshowDescription;
var eSlideshowPrice;
var iSlideshowDelay = 9000; 

function slideshowInit() {
	 	
	eSlideshow = $('#homepage-slideshow');
	
	if (!eSlideshow) {
		return false;
	}
   	
	eSlideshowImageBackground = eSlideshow.children('.background');
	eSlideshowImageForeground = eSlideshow.children('.foreground');
	eSlideshowContent = eSlideshow.children('.content');
	eSlideshowTitle = eSlideshowContent.children('.title');
	eSlideshowDescription = eSlideshowContent.children('.description');
	eSlideshowPrice = eSlideshowContent.children('.price');
    
	for (var j = 0; j < aSlides.length; j++) {
		$.preloadImage(aSlides[j].image);
	}
	
	setTimeout(slideshowNext, iSlideshowDelay);
}

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

function slideshowNext() {
	slideshowShow(iSlideCurrent+1);
	
	setTimeout(slideshowNext, iSlideshowDelay);
}

function slideshowShow(i) {
	
	i = slideshowGetIndex(i);
	
	if (iSlideCurrent == i) {
		return;
	}
	
	eSlideshowImageBackground.attr('src', aSlides[i].image);
	
	eSlideshowContent.fadeOut(300, function() {
		slideshowSetContent(i);
		eSlideshowContent.fadeIn(400);		
	});
	                         
	eSlideshowImageForeground.fadeOut(700, function() {
		eSlideshowImageForeground.attr('src', aSlides[i].image);
		eSlideshowImageForeground.show();		
	});
 	
   	iSlideCurrent = i;
}

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

// Image preload

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

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

// Recent Newss

var RNFadeout = 180;
var RNSlide = 400;
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: '750px'
            
        }).show().animate({
            marginLeft: '0px'
            
        }, RNSlide);
    });
    
    setTimeout(switchNews, RNFadeout + RNSlide + RNSwitch);
}

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

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

// Price enquiry

function priceEnquiryShow(){
	$('#price-enquiry > .button').hide();
	$('#price-enquiry > .form-container').slideDown();
	return false;
}

function priceEnquiryHide(){
	$('#price-enquiry > .form-container').slideUp(false, function(){
		$('#price-enquiry > .button').fadeIn();	
	});
	return false;
}

function priceEnquirySubmit(eForm){
	eForm = $(eForm);

	eForm.children('.form').addClass('loading');
	$('#price-enquiry > .form-container .error').slideUp();
	
	$.post(eForm.attr('action') + '?ajax',
		eForm.serialize(),
		function(data){
			
			eForm.children('.form').removeClass('loading');

			if (data.message) {
				eForm.remove();
				$('#price-enquiry > .form-container > .message').html(data.message).fadeIn();
			}
			
			if (!data.result && data.errors) {				
				for (sField in data.errors) {
					$('#price_enquiry_' + sField).parent().siblings('.error').html(data.errors[sField]).slideDown();
				}
			}
		},
		"json"
	);

	return false;
}
