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

$(document).ready(function () {
    $('#accordion').accordeonMenu();        

    $('#search_form').submit(function () {
        var criteria = $('#search_criteria').val();

        if (!criteria) {
            return false;
        }

        // append search criteria to uri
        var search_url = $(this).attr('action') + '/' + encodeURI(criteria);

        $(this).attr('action', search_url);

        return true;
    });

    $('.edit_content').nyroModal({
        width: 700,
        height: 300
    });

    $('.gallery').bpGallery();


	$('#map > area').mouseover(function(){
		var koef = parseInt($(this).attr('id').replace('a',''))*-395;
		$('#mapdiv').css('background-position',koef+'px 0');
	});

	// feedback form steps switcher
	$('.pager .ahead,.pager .ago').click(function() {
		//validation
		if( !$(this).hasClass('ago') ) {
			// step1 index
			$('#errors').hide();
			if( $('#step1').length != 0 ) {
				if($('#start_year').val().length < 1 || $('#how_often_weekmultiple').val().length < 1 ) {
					$('#errors').fadeIn();
					return false;
				}
			}
			// step2
			$('#errors').hide();
			if( $('#step2').length != 0 ) {
				if($('#step2').find('.ul3 :checkbox:checked').length < 1 && $('#reason_other').val().length < 1) {
					$('#errors').fadeIn();
					return false;
				}
			}
			// step3
			if( $('#step3').length != 0 ) {
				if($('#step3').find('.ul3 :radio:checked').length < 1 ) {
					$('#errors').fadeIn();
					return false;
				}
			}
			// step4
			if( $('#step4').length != 0 ) {
				if($('#step4').find('.cb :radio:checked').length < 2 ) {
					$('#errors').fadeIn();
					return false;
				}
			}
		}
		$('input[name="data[Feedback][satisfaction]"]').val( $('.slider').slider('option', 'value') );
		$(this).closest('form').attr('action', $(this).attr('href')).submit();
		return false;
	}); 

	if( $('.slider').length != 0 ) {
		$('.slider').slider({ max: 10, value : $('input[name="data[Feedback][satisfaction]"]').val() });
	}
	
    if ($.fn.datepicker) {
        $("#feedback_form input[name='data[Feedback][birthday]']").datepicker( { dateFormat: 'dd/mm/yy', firstDay: 1 , changeYear: true, changeMonth: true, yearRange: '1920:2010'} );

        $('.datepicker').click(function(){
            $("#feedback_form input[name='data[Feedback][birthday]']").datepicker("show");
            return false;
        });
    }
	// appointment form validation
	$("#feedback_form").submit(function(){
		var result = true;
		
		$(this).find('.required').removeClass('invalid').each(function(){
			if( $(this).val().length == 0 ) {
				$(this).addClass('invalid');
				result = false;
				$('#errors').fadeIn();
			}
			var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; 
			if($(this).attr('name') == 'email' && !emailPattern.test($(this).val()) ) {
				$(this).addClass('invalid');
				result = false;
				$('#errors').fadeIn();
			}
		});
		
		return result;
	});
});


