/**
 *
 * Custom js (jQuery) functions of the application
 *
 */

String.prototype.ellipsis = function (limit) {
    var center = ' ... ';
    var len = this.length;
    if (len > limit) {
        var half = Math.floor( (limit - center.length)/2 );
        return this.substr(0, half) + center + this.substr(len-half, half);
    }
    return this.toString();
}

jQuery.extend(jQuery.fn, {
    initCart : function () {
        var _this = $(this);
        _this.find('#pr_amount').tooltip({
            bodyHandler: function () {
                return _this.find('#cart_items').html();
            },
            showURL: false
        });
    },
    poller : function () {
        var _this = $(this);
        var voted = $.cookie('CakeCookie[voted]');
        var inputs = _this.find('input');

        if (voted) {
            inputs.hide();
        } else {
            inputs.show();
            _this.ajaxForm({
                beforeSubmit : function () {
                    $.blockUI({message : false});
                },
                success : function (response) {
                    $.unblockUI();
                    inputs.hide();
                    response = eval('(' + response + ')');
                    for (var i=0; i < response.PollersOption.length; i++) {
                        _this
                            .find('#votes_' + response.PollersOption[i].id)
                            .text(response.PollersOption[i].votes_percentage);
                    }
                }
            });
        }
    },
    bpGallery : function () {
        var gallery  = $(this);
        var main_img = gallery.find('> a');
        main_img.attr('rel', 'gal');
        var container = $('<div style="display:none"></div>').appendTo(gallery);
        var thumbs   = gallery.find('> ul > li > img');
        thumbs.each(function (index) {
            $('<a></a>')
                .attr('href', $(this).attr('alt'))
                .text(index)
                .appendTo(container);
        });
        var links  = container.find('> a');
        thumbs.click(function () {
            var src = $(this).attr('alt');
            main_img.attr('href', src);
            main_img.find('img').attr('src', src);
            return false;
        });
        main_img.click(function () {
            links.attr('rel', 'gal');
            // don't repeat the main image in the gallery
            links.filter("[href='" + main_img.attr('href')  + "']").attr('rel', '');
        });
    },
    // simple accordeon menu
    accordeonMenu : function () {
        var menu = $(this);
        $('> li > a:not(.active) ~ .sub', menu).hide();
        var items = $('> li > a', menu).click(function () {
            items.removeClass('active');
            $(this).addClass('active').siblings('.sub').slideDown('normal');
            items.not('.active').siblings('.sub').slideUp('normal');
        });
        return menu;
    },
    digitsOnly : function () {
        var $this = $(this);
        $this.keypress(function (e) {
            // allow digits only
            if (e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) {
                return false;
            }
        });
        return $this;
    },
    advForm : function (options) {
        // main settings
        var settings = $.extend({
            validate          : false,
            ajax              : false,
            sent_message      : 'please wait...',
            error_message     : 'your message was rejected',
            highlight         : false,
            highlight_message : 'please fill the fields in red',
            highlight_class   : 'required'
        }, options);

        if (!settings.validate && !settings.ajax) {
            return true;
        }

        var _form = $(this);

        // params to pass to the validation plugin
        var validation_settings = {
            errorClass   : 'error-message',
            errorElement : 'div',
            highlight    : false
        };

        if (settings.highlight === true) {
            delete validation_settings.highlight;
            validation_settings = $.extend(validation_settings, {
                showErrors : function (errors) {
                    for ( var i = 0; this.errorList[i]; i++ ) {
                        var error = this.errorList[i];
                        if (typeof this.settings.highlight == 'function') {
                            this.settings.highlight.call( this, error.element, settings.highlight_class );
                        }
                    }
                    for ( var i = 0, elements = this.validElements(); elements[i]; i++ ) {
                        this.settings.unhighlight.call( this, elements[i], settings.highlight_class );
                    }
                    if (_form.find('.' + settings.highlight_class).length > 0) {
                        _form.find('.form_status').text(settings.highlight_message);
                    } else {
                        _form.find('.form_status').text('');
                    }
                }
            });
        }

        $.metadata.setType('attr', 'validation');

        if (settings.validate && !settings.ajax) {
            _form.validate(validation_settings);
            return true;
        }

        if (settings.ajax) {
            var createMessage = function (text) {
                return '<div class=\"wait_message\">' + text + '</div>';
            }
            _form.ajaxForm({
                beforeSubmit : function () {
                    if (settings.validate && !_form.validate(validation_settings).form()) {
                        return false;
                    }
                    $.blockUI({ message : createMessage(settings.sent_message) });
                },
                success : function (data, status) {
                    setTimeout(function () {
                        $.unblockUI();
                        _form.resetForm();
                    },2000);
                }
            });

            _form.ajaxError(function () {
                $.blockUI({ message : createMessage(settings.error_message) });
                $.unblockUI({ fadeOut : 4000});
            });

            return true;
        }
    },
    loadCart : function () {
        var $this = $(this);
        $.ajaxSetup({cache: false}); // need this for damned ies
        $this.load('/cart/show', function () {
            $('#pr_amount', this).tooltip({
                bodyHandler: function () {
                    return $('#cart_items', $this).html();
                },
                showURL: false
            });
        });
    }
});

function browserCheck(locale) {
	var teststr = /MSIE 6\.0/;
	if(teststr.test(navigator.userAgent)) {
        $.nyroModalManual({
            url       : '/' + locale + '/pages/browser',
            endRemove : function() {
                browserCheck(locale);
            }
        });
	}
}

// custom validation rules and settings
if ($.validator) {


    $.validator.setDefaults({
        onkeyup      : false,
        highlight    : false,
        errorElement : 'div',
        errorClass   : 'error-message'
    });

}

$.ajaxSetup({
  cache: true
});

$(document).ready(function () {
	// set the page background
	if(typeof(Backgrounds)!='undefined') {
		if(Backgrounds.length>0)
			$('body').css('background-image', 'url(/img/images/'+Backgrounds[0]+')');
	}

	// hide the mainmenu and show it again with animation
	$("#mainmenu").slideDown(1000);

    var window_height;
	var content_height = 809;
	window_height = $(window).height();
	if (window_height > 809){
		content_height = window_height;
	}
//	$('#header, .content_inside').css("height",content_height);
	$('#header').css("height",content_height);

	$('#content .index_entrys a div').css({'opacity':'0.2'});
	$('#content .index_entrys a div').hover(
		function(){
			$(this).css({'opacity':'1.0'});
		},
		function(){
			$(this).css({'opacity':'0.2'});
		}
	);

	$('#nautic_list').jScrollPane({
		dragMaxHeight : 72,
		scrollbarWidth: 11
	});

	$('ul.list').jScrollPane({
		dragMinHeight : 72,
		dragMaxHeight : 72,
		scrollbarWidth: 11
	});

	//set all links wich has no '#' ajaxify
	$("a[href!='#']").live('click', function(){
		//get the contents of the page this link is targeted to
		if($(this).attr('href')!='/' &&
         $(this).attr('rel')!='dl' &&
		 !$(this).closest('ul').hasClass('lang') &&
		 $(this).closest('ul').attr('id')!='nautic_list' &&
		 !$(this).closest('ul').hasClass('list')
		 ) {
			put_contents($(this).attr('href'));
			return false;
		}
	});

	if(document.location.hash) {
		put_contents(document.location.hash.replace('#', ''));
	}

	// autocomplete
	$("#search").autocomplete($('.lang a.on').attr('href')+'/products/autocomplete/', {
		autoFill : false,
		cacheLength : 512,
		max : 100,
		minChars : 3,
		delay : 600,
		scroll : true,
		scrollHeight : 220
	});

	// start searching after option is selected
	$('#search').result(function(event, data, formatted) {
		$(".search_form").submit();
	});

	// gallery
	if(typeof(reference_images)!='undefined') {
		if(reference_images.length>0) {
			show_image(0);
		}
	}

	$("#gallery .prev").live("click", function(){
		show_image((current_image-1)>=0? current_image-1 : reference_images.length-1);
		return false;
	});

	$("#gallery .next, .image_link").live("click", function(){
		show_image((current_image+1<reference_images.length)? current_image+1 : 0);
		return false;
	});

	// click on the products preview
	$("#nautic_list a, ul.list a").live("click", function(){
		document.location.hash=$(this).attr('href');
		$("#nautic_list li").removeClass('on');
		$("#nautic_list a[href='"+$(this).attr('href')+"']").closest('li').addClass('on');
		if($(this).closest('ul').hasClass('list')) {
			$("#nautic_list")[0].scrollTo( 'li.on', 800 );
		}
		$('body').append('<img id="ajaxloader" src="/img/layout/preloader.gif" alt="" style="position:fixed;z-index:100000;top:50%;left:60%;"/>');
		$('.nautic_detail').slideUp().load($(this).attr('href')+' .nautic_detail > *', function(){
			document.title = 'tekna.be - '+$('.nautic_title').html();
			$("#ajaxloader").remove();
			$(this).slideDown(800);
			$('ul.list').jScrollPane({
				dragMinHeight : 72,
				dragMaxHeight : 72,
				scrollbarWidth: 11
			});
		});
		return false;
	});

	// scroll to active product preview
	if($("#nautic_list").length>0)
		$("#nautic_list")[0].scrollTo( 'li.on', 800 );

	// mainmenu click
	$("#mainmenu a").click(function(){
		$(this).closest('ul').find('li').removeClass('on');
		$(this).closest('li').addClass('on');
		Cufon.replace("#mainmenu li", {hover: true});
	});
});

var current_image=0;

function show_image(index) {
	current_image=index;
	$("#gallery .image").attr('src', '/img/images/'+reference_images[index]['image']);
	$("#gallery .count").html( (index+1) + '/' + reference_images.length);
	$("#gallery .title").html(reference_images[index]['title']);
	$("#gallery .text").html(reference_images[index]['description']);
}

function put_contents(href) {
	$(".content_inside").fadeOut(500, function(){
		$('body').append('<img id="ajaxloader" src="/img/layout/preloader.gif" alt="" style="position:fixed;z-index:100000;top:50%;left:50%;"/>');
	});
	$.get(href, function(response){
			// change #content class
			if(href.indexOf('/products/p')!=-1 || href.indexOf('/products/g')!=-1) {
				$("#content").removeClass('content_type2').addClass('content_type3');
			}
			else if(href.indexOf('/news')!=-1 && /news\/\d/.test(href)) {
				$("#content").removeClass('content_type3').addClass('content_type2');
			} else {
				$("#content").removeClass('content_type3').removeClass('content_type2');
			}
			$('.content_inside').html(response).fadeIn(500, function(){
				$("#ajaxloader").remove();
				if($('#nautic_list').length!=0) {
					$('#nautic_list').jScrollPane({
						dragMaxHeight : 72,
						scrollbarWidth: 11
					});
				}
				document.location.hash=href;
				// change background
				if(typeof(Backgrounds)!='undefined') {
					if(Backgrounds.length>0)
					$('body').css('background-image', 'url(/img/images/'+Backgrounds[Math.floor(Math.random()*Backgrounds.length)]+')').height($(".content_inside").height());
				}

			});
			// window title for products
			document.title = 'tekna.be';
			if($('.nautic_title').length != 0)
				document.title = 'tekna.be - '+$('.nautic_title').html();
			if($('.title').length != 0)
				document.title = 'tekna.be - '+$('.title').html();
			if($('.cont > h2').length != 0)
				document.title = 'tekna.be - '+$('.cont > h2').html();
			// gallery reinit
			if(typeof(reference_images)!='undefined') {
				if(reference_images.length>0) {
					show_image(0);
				}
			}
			// home page css reinit
			$('#content .index_entrys a div').css({'opacity':'0.2'});
			$('#content .index_entrys a div').hover(
				function(){
					$(this).css({'opacity':'1.0'});
				},
				function(){
					$(this).css({'opacity':'0.2'});
				}
			);
			$('ul.list').jScrollPane({
				dragMinHeight : 72,
				dragMaxHeight : 72,
				scrollbarWidth: 11
			});
	});
}

Cufon.replace("#mainmenu li", {hover: true});

