/**
 * Extended method for String class
 *
 * @param integer limit - max string length
 * @return string - original string with '...' in the middle instead of excess chars
 */
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();
};

String.prototype.trim = function() {
	return this.replace(/(^\s+)|(\s+$)/g, "");
}

function generatePwd(length) {
	chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
	pass = "";
	for(x=0;x<length;x++) {
		i = Math.floor(Math.random() * 62);
		pass += chars.charAt(i);
	}
	return pass;
}

/**
 * Send data (id and value) to a url on change
 *
 * @author Yuriy Kharchenko
 */

$.fn.ajaxCheckbox = function (url) {
    $(this).change(function () {
        $.blockUI();
        $.post(url, {
            'data[id]' : $(this).val(),
            'data[value]' : $(this).attr('checked') ? 1 : 0
        }, function () {
            $.unblockUI();
        })
    });
}//eof
/**
 * Usage
 * html:
 *   <input id="UserName"... name="data[User][name]" />
 * js:
 *   data = {};
 *   $('#UserName').valTo(data);
 *   $.post('/test', data)
 * php:
 *   $this->data['User']['name']
 */

$.fn.valTo = function (data, options) {
    var settings = {
        _default : ''
    };
    if(options) {
        $.extend(settings, options);
    }
    var value = $(this).val();
    data[ $(this).attr('name') ] = value ? value : settings._default;
    return data;
};

jQuery.fn.tap = function(fn /* [callback_arg], [callback_arg], [...] */) {
    var args = jQuery.makeArray(arguments);
    args.unshift();

    fn.apply(this, args);
    return this;
};
/**
 *
 * Adds 'hover' class to an element - fix for ie
 *
 */

$.fn.hoverable = function () {
    return this.each(function () {
        var _this = $(this);
        _this.hover(
            function () {
                _this.addClass('hover');
            },
            function () {
                _this.removeClass('hover');
            }
        );
        return _this;
    });
};


$.fn.replaceClass = function(oldClass, newClass) {
   if ( $(this).hasClass(oldClass) ) {
        $(this).removeClass(oldClass).addClass(newClass);
   }
};


/**
 * Used in dynamic tables (like in products edit)
 */

$.fn.remover = function (selector) {
    $(selector, this).click(function () {
        $(this).parent('td').parent('tr').remove();
        return false;
    });
};


/**
 * Used in dynamic tables (like in products edit)
 */

$.fn.appender = function (selector, source, session_id, callback) {
    source = $(source);
    var $this = $(this);
    $(selector, this).click(function () {
        var sample = $('tr:first', source).clone();
        sample.remover('.remove');

        var index = $('tr.input', $this).length;
        // replace '%d' with indexes
        $('.to_replace, input', sample)
            .each(function () {
				if ( $(this).attr('id') ) {
	                $(this).attr({
	                	'id' : $(this).attr('id').replace('%d', index),
	                    'name' : $(this).attr('name').replace('%d', index),
	                    'disabled' : false
	                });
	                if (callback !== undefined) {
	                    callback(this);
	                }
				}
            })
            .removeClass('to_replace');
        //multiple swf upload
        $('.file-name', sample).each(function() {
            $(this).parent().find('.to_replace_id').each(function() {
                $(this).attr('id', $(this).attr('id').replace('%d', index)).removeClass('to_replace_id');
            });
            $(this).parent().find('input:hidden').each(function() {
                $(this).attr({
                    'name': $(this).attr('name').replace('%d', index),
                    'disabled': false
                });
            });

            var swfu;

            settings = {
            // General Settings
            upload_url : "/heartbeat/fileobjs/upload/" + session_id,
            flash_url : "/swf/swfupload.swf",
            debug: false,

            // Upload button
            button_placeholder_id : "swfuploadbtn" + index,
            button_image_url : "/img/icons/add-swfu.png",
            button_width : "25",
            button_height : "25",

            // File Upload Settings
            file_types : "*.doc",
            file_types_description : "Files",
            file_upload_limit : 0,
            file_size_limit : "60 MB",

            // Callbacks
            file_dialog_complete_handler : fileDialogComplete,
            upload_error_handler : uploadError,
            upload_success_handler : uploadSuccess,
            upload_progress_handler : uploadProgress,

            // Custom
            customSettings: {
                uploadId : index
            }
            };

            //swfu = new SWFUpload(settings);
        });
        //eof multiple swf upload
        $('.datepicker', sample)
            .each(function () {
                $(this).datepicker()
                .parent().find('button').click(function(){
                    $(this).parent().find('input').datepicker("show");
                    return false;
                });
            });
        sample.appendTo($this);
        sample.find('.file-name:first').each(function() {
            swfu = new SWFUpload(settings);
        });
        return false;
    });
};


/**
 * Make an input accept only digits
 */

$.fn.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;
};

$.fn.nonEmptyCheckbox = function () {
    var inputs = $(this).find(':checkbox');
    inputs.click(function () {
        if (inputs.filter(':checked').length < 1) {
            $(this).attr('checked', 'checked');
        }
    });
};


$.fn.selectAll = function (selector) {
    $(this).click(function () {
        $(selector).attr('checked', $(this).attr('checked') ? true : false);
    });
};


$.fn.nestedCheckbox = function (options) {
    var $this = $(this);
    var settings = $.extend({
        nodeIdAttr : 'node_id',
        parentIdAttr : 'parent_id'
    }, options);

    $this.click(function () {
        checkChildren($(this));
    });

    function checkChildren(el) {
        var node_id = el.attr(settings.nodeIdAttr);
        var checked = el.is(':checked');
        $this.filter('[' + settings.parentIdAttr + '=' + node_id + ']').each(function () {
            var _el = $(this);
            _el.attr('checked', checked ? 'checked' : null);
            checkChildren(_el);
        });
    }
};

// A small extension for Fancybox plugin.
// You can open a popup manually like this: $.fancybox.open({ href : 'whatever.php' });
// so you don't need to have the triggering element.
if ($.fancybox) {
    $.fancybox.open = function (options) {
        if (options.href == undefined) {
            return;
        }
        $('<a href="javascript:void(0);"></a>').fancybox(options).trigger('click');
    };
}


/* Menu plugin */
(function($){
    $.mainMenu = function () {
        var max = App.menu.max,
            visible = App.menu.visible,
            l_key = 'CakeCookie[left_menu_pos]',
            r_key = 'CakeCookie[right_menu_pos]',
            left  = $.cookie(l_key) ? $.cookie(l_key) : 0,
            right = $.cookie(r_key) ? $.cookie(r_key) : visible -1;

        function checkActive() {
            if (right >= max) {
                $('#rightMenuArrow').removeClass('rightUp').addClass('rightInactive');
            } else {
                $('#rightMenuArrow').removeClass('rightInactive').addClass('rightUp');
            }

            if (left > 0) {
                $('#leftMenuArrow').removeClass('leftInactive').addClass('leftUp');
            } else {
                $('#leftMenuArrow').removeClass('leftUp').addClass('leftInactive');
            }
        }

        function savePosition() {
           $.cookie(l_key , left, {path: '/'});
           $.cookie(r_key, right, {path: '/'});
        }

        var menu = $('#menu > ul.menu');

        var subm = menu.find('ul.submenu');

        var li = menu.find('> li').not('.menuShift');

        subm.each(function () {
            var _this = $(this);
            _this.find('li:last').addClass('last');
            _this.hover(function () {
                $(this).parent('li').not('.current').addClass('active');
            }, function () {
                $(this).parent('li').not('.current').removeClass('active');
            });
        });

        $('#active_submenu').parent('ul').parent('li').addClass('active current');

        li.each(function () {
             var _this = $(this);
            _this.hover(function () {
                $(this).siblings('li.active').removeClass('active');
            }, function () {
                $(this).siblings('li.current').addClass('active');
            });
            _this.click(function () {
                $(this)
                    .addClass('active current')
                    .siblings('li').not('.menuShift').removeClass('active current');
            });
            _this.hoverable();
        });
        li.filter(':gt('+right+')').hide();
        li.filter(':lt('+left+')').hide();

        checkActive();

        $('#rightMenuArrow')
            .click(function () {
                if (right < max) {
                    right++;
                    li.filter(':eq('+right+')').show(300);
                    li.filter(':eq('+left+')').hide(300);
                    left++;
                }
                checkActive();
                savePosition();
            })
            .mousedown(function () {$(this).replaceClass('rightUp', 'rightDown');})
            .mouseup(function () {$(this).replaceClass('rightDown', 'rightUp');});

        $('#leftMenuArrow')
            .click(function () {
                if (left > 0) {
                    left--;
                    li.filter(':eq('+left+')').show(300);
                    li.filter(':eq('+right+')').hide(300);
                    right--;
                }
                checkActive();
                savePosition();
            })
            .mousedown(function () {$(this).replaceClass('leftUp', 'leftDown');})
            .mouseup(function () {$(this).replaceClass('leftDown', 'leftUp');});

        menu.show();
    }
})(jQuery);

function browserCheck(url) {
	var Browser = {
	  	Version: function() {
	    	var version = 999; // we assume a sane browser
	    	if (navigator.appVersion.indexOf("MSIE") != -1)
	      	// bah, IE again, lets downgrade version number
	      	version = parseFloat(navigator.appVersion.split("MSIE")[1]);
	    	return version;
	  	}
	}
	if(Browser.Version() < 9) {
		$('#browser_upgrade_bar').load(url);
	}
}

// Hightligh TAB label if error happens on tabbed form
function highlightErrorTab(validator, errorMap, errorList) {
	var tab_name;
	this.defaultShowErrors();

	try {
		$('ul.tab_header li').each(function() {$(this).removeClass('tab-error-message');});
		for(var x in errorMap) {
			tab_name = $(errorMap[x]['element']).closest('div.shadowed').attr("id");
			$('a[href="#' + tab_name + '"]').closest('li').addClass('tab-error-message');
		}
	} catch(e) {}
}

$.delay = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();

// app defaults
$(document).ready(function () {
    // set defaults for blockUI jQuery plugin
    $.blockUI.defaults.message = false;

	$('span.token a').fancybox({
        'width'  : 540,
        'height' : 420,
        'type'   : 'iframe'
	});


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

//    $('a.hint').fancybox();
    if (jQuery().tipsy) {
        $('a.hint').mouseenter(function(){
            $(this).tipsy('show');
        });
        $('div.tipsy').live('mouseleave', function(){
            $('a.hint').tipsy('hide');
        });
        $('body').click(function() {
            $('a.hint').tipsy('hide');
        });
        $('a.hint').tipsy({
            gravity: 'nw',
            trigger: 'manual',
            html: true,
            title: function(){
                var id = $(this).attr('href').split('#')[1]
                return $('#' + id).html();
            }
        });
    }

	$('.datepicker').datepicker({showButtonPanel:true, buttonImageOnly: true, dateFormat: 'dd/mm/yy'});
	$('.timepicker').timepicker(true);

	$('.non_empty_checkbox').nonEmptyCheckbox();

    if ($.datepicker) {
        $.datepicker.setDefaults({
            dateFormat  : App.date_format,
            buttonImage : App.base_url + '/img/layout/calendar.png',
            changeMonth : true,
            changeYear  : true
        });
    }

	$('#view .btn-delete').click(function() {
		var _this = $(this);

        if(_this.hasClass('custom_dialog')) {
            return false;
        }

        var href = _this.attr('href');
        href = href.substring(0, href.indexOf('/delete'));
        if (href == '') {
            return true;
        }
        $.get(href + '/checkMedia', function(data) {
            $('#delete_panel input:radio').enable();

        	switch(data) {
                case '':
                    $('#Option2, #Option3, #Option4').disable();
                    break;
        	    case 'images':
            	    $('#Option3, #Option4').disable();
            	    break;
                case 'files':
                    $('#Option2, #Option4').disable();
                    break;
        	}

        	if(data) {
        		$.fancybox($('#delete_panel').html(), {
        			onComplete : function() {
                        $('#fancybox-content .dp_cancel').one('click', function() {
                        	$.fancybox.close();
                        });

                        $('#fancybox-content .dp_confirm').one('click', function() {
            	    		if(confirm(App.areyousure)) {
            	    			var mode = $('#fancybox-content input:radio').val();

            	    			location.href = _this.attr('href') + '/mode:' + mode;
            	    		}
            	    		$.fancybox.close();
                        });
                	}
        		});
        	} else {
        		if(confirm(App.areyousure)) {
        			location.href = _this.attr('href');
        		}
        	}
        });

        return false;
    });

	browserCheck("/heartbeat/statics/browser");

	// Refresh session requests
	App.RefreshSession = function() {

	  /**
	   * Interval object used to call refresh function
	   */
	  var refresh_interval = null;

	  // Return value
	  return {

	    /**
	     * Initialize refresh interval
	     *
	     * @params void
	     * @return boolean true if sesslion refresh handler is set
	     *                 and false otherwise.
	     */
	    init : function() {
	      if(App.keep_alive_interval > 0) {
	        refresh_interval = setInterval('App.RefreshSession.refresh()', App.keep_alive_interval);
	        return true;
	      } // if
	      return false;
	    },

	    /**
	     * Function used to refresh session
	     *
	     * @param void
	     * @return null
	     */
	    refresh : function() {
	      $.ajax({
	        url : App.refresh_session_url
	      });
	    }
	  }

	}();


	if (!App.RefreshSession.init()) {
		//If keap session alive interval is not set -
		// use timeout window.
		var patt = /(\/add|\/edit|\/create)/;
		if(patt.test(location.href)) {
	        setTimeout(function() {
	            $.fancybox($('#timeout_coming_panel').html());
	        }, App.timeout);
		}
	}

	jQuery('a.minibutton').bind({
		mousedown: function() {
			jQuery(this).addClass('mousedown');

		},
		blur: function() {
			jQuery(this).removeClass('mousedown');
		},
		mouseup: function() {
			jQuery(this).removeClass('mousedown');
		}
	});

	jQuery('a.submitbtn').bind({
		mouseup: function() {
			$(this).parents('form:first').submit();
		}
	});

	jQuery('a.clearresults').bind({
		mousedown: function() {
			$(this).parents('form').find(':input:visible').each(function() {
                $(this).val('');
			});
		}
	});

	$('form').keypress(function(event){
	    var keycode = (event.keyCode ? event.keyCode : event.which);

	    if(keycode == '13' && $(event.target)[0].type != 'textarea'){
	    	this.submit();
	    }
	});

	var radio = $('#delete_panel input:radio');
	if(radio.length) {
		radio.disable();
	}

	$('#debug_level_select').change(function() {
		var value = $(this).val();

	    $.post('/heartbeat/systems/wizard', {'data[Backend][System][debug]' : value}, function() {
	    	location.reload();
	    });
	});

	$('.records_per_page').find('select').change(function() {
		var _this = $(this);
		var value = _this.val();

		_this.parent('form').submit();
	});

	if ($.browser.msie) $('select')
	    .bind('focus mouseover', function() {$(this).addClass('expand').removeClass('clicked');})
	    .bind('click', function() {$(this).toggleClass('clicked');})
	    .bind('mouseout', function() {if (!$(this).hasClass('clicked')) {$(this).removeClass('expand');}})
	    .bind('blur', function() {$(this).removeClass('expand clicked');});

});

