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

function get_dictionary(key) {
	if(typeof(dictionary) != 'undefined' && typeof(dictionary[key]) != 'undefined') {
		return dictionary[key];
	} else {
		// add this key to db
		$.get('/system/add_dictionary', {key : key});
		return key;
	}
}

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');
        var progress = _this.find('span.progressbar');
        var settings = {
            height   : 12,
            width    : 90,
            boxImage : "/img/layout/progressbar.gif",
            barImage : "/img/layout/progressbg_green.gif"
        };
        
        function initResults() {
        	progress.each(function() {
                var val = $(this).attr('data')
                $(this).show().progressBar(val, settings);
            });
        }

        if(voted) {
            inputs.hide();
            initResults()
        } else {
            inputs.show();
            progress.hide();
            _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)
                            .attr('data', response.PollersOption[i].votes_percentage);
                    }
                    initResults();
                    $('#total_votes', _this).html(response.PollersItem.total_votes);
                }
            });
        }
    },
    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.find('.f1').text(get_dictionary('sent_message'));
                        _form.resetForm();
                    },2000);
                }
            });

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

            return true;
        }
    }
});

$(document).ready(function(){
    $('nav a').hoverIntent(function(){
        $(this).animate({
            'top':'-23px'
        },200);
    },function(){
        $(this).animate({
            'top':'0'
        },200,function(){
            $(this).css('top',0)
        })
    })
    
    $('.slider .inS').cycle({
        timeout : 4000,
        fx : 'scrollHorz',
        prev : '.prev',
        next : '.next'
    });
    $('.submitbtn').click(function() {
		$(this).parents('form').submit();
	}); 
});
