/// <reference path="jquery-1.4.1-vsdoc.js" />

Date.prototype.format = function(format) {
    retur = format.
    replace('dd', $.fonqi.precedeZero(this.getDate())).
    replace('d', this.getDate()).
    replace('MM', $.fonqi.precedeZero(this.getMonth() + 1)).
    replace('yyyy', this.getFullYear()).
    replace('yyy', this.getFullYear().toString().substr(1)).
    replace('yy', this.getFullYear().toString().substr(2)).
    replace('y', this.getFullYear().toString().substr(3)).
    replace('hh', $.fonqi.precedeZero(this.getHours())).
    replace('ss', $.fonqi.precedeZero(this.getSeconds())).
    replace('mm', $.fonqi.precedeZero(this.getMinutes()));
    return retur;
}
Array.prototype.contains = function(obj) {
    var contains = false;
    $(this).each(function(index, value) {
    if (value === obj) { contains = true; }
    });
    return contains;
}
$.extend({
    fonqi: {
        dating: {
            now: function(format) {
                var _date = new Date();
                if (arguments.length === 0 || (arguments.length == 1 && $.fonqi.validation.isEmpty(arguments[0]))) {
                    $.fonqi.trace(_date);
                    return _date;
                }
                else {
                    return $.fonqi.dating.formatDate(_date, format);
                }
            },
            formatDate: function(_date, format) {
                return _date.format(format);
            }
        },
        mouse: {
            x: function(evt) {
                if (!evt) { evt = window.event; }
                if (evt.pageX) { return evt.pageX; }
                else if (evt.clientX) { return evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft); }
                else { return 0; }
            },
            y: function(evt) {
                if (!evt) { evt = window.event; }
                if (evt.pageY) { return evt.pageY; }
                else if (evt.clientY) { return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); }
                else { return 0; }
            }
        },
        validation:
	    {
	        isEmpty: function(str) {
	            if (str == null) { return true; }
	            else { return (str.replace(/^\s+/, '').length < 1); }
	        },
	        isEmail: function(str) {
	            return (str.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1);
	        },
	        isValueInArray: function(array, value) {
	            return array.contains(value);
	            /*for (var i = 0; i < array.length; i++) {
	            if (array[i] == value) {
	            return true;
	            }
	            }
	            return false;*/
	        }
	    },
        precedeZero: function(number) {
            if (number < 10)
            { return "0" + number; }
            return number;
        },

        decimals: function(val, decimals) {
            var power = Math.pow(10, decimals);
            return Math.round(val * power) / power;
        },

        request: function(value) {
            var queryStr = location.href.split('?');
            if (queryStr.length < 2)
            { return null; }
            var requestObj = {};
            var level1 = [];
            level1 = queryStr[1].split('&');
            for (var i = 0; i < level1.length; i++) {
                level2 = level1[i].split('=');
                requestObj[level2[0]] = level2[1];
            }
            return requestObj[value];
        },
        delay: function(func, seconds) {
            setTimeout(func, seconds);
        },
        repeat: function(func, seconds, times) {
            if (arguments.length == 2)
            { return window.setInterval(func, seconds); }
            else {
                $.counter = times;
                var interval = window.setInterval(func, seconds);
                var counterval = window.setInterval("$.counter--; if($.counter == 0) {window.clearInterval(" + interval + "); window.clearInterval(" + counterval + ")}", seconds);
                return counterval;
            }
        },
        stopRepeat: function(id) {
            window.clearInterval(id);
        },
        fadeToLocation: function(url) {
            var faderdiv = $('<div></div>');
            var bgcolor = '#FFF';
            faderdiv.css({
                'backgroundColor': bgcolor,
                'width': '100%',
                'height': '100%',
                'position': 'fixed',
                'top': '0',
                'left': '0',
                'zIndex': '9999'
            });
            faderdiv.alpha(0);
            $("body").append(faderdiv);
            faderdiv.animate({
                opacity: 1
            }, 1000, function() {
                location.href = url;
            });
        },
        inspect: function(obj) {
            var str = "";
            for (var prop in obj) {
                if (prop !== null) {
                    str += "prop: " + prop + " = '" + obj[prop] + "'<br />";
                }
            }
            $.fonqi.trace(str);
        },
        trace: function(message) {
            var alertDiv = $("#tracerdiv");

            var closeBtn = $("#closebtn");
            var traces = $("#traces");
            if ($("#tracerdiv").length === 0) {
                alertDiv = $("<div id='tracerdiv'></div>");
                closeBtn = $("<div id='closebtn'>X</div>");
                clearBtn = $("<div id='cleatbtn'>C</div>");
                traces = $("<div id='traces'></div>");
                alertDiv.append(closeBtn).append(clearBtn).append(traces);
                closeBtn.toggle(traces);
                clearBtn.click(function() { traces.html(""); });
                closeBtn.css
			    ({
			        'lineheight': '0.6',
			        'cursor': 'pointer',
			        'color': '#666',
			        'border': '1px solid #666',
			        'width': '10px',
			        'height': '12px',
			        'position': 'absolute',
			        'left': '2px',
			        'top': '2px',
			        'text-align': 'center',
			        'padding': '1px'
			    });
                clearBtn.css
			    ({
			        'lineheight': '0.6',
			        'cursor': 'pointer',
			        'color': '#666',
			        'border': '1px solid #666',
			        'width': '10px',
			        'height': '12px',
			        'position': 'absolute',
			        'left': '18px',
			        'top': '2px',
			        'text-align': 'center',
			        'padding': '1px'
			    });
                alertDiv.css
			    ({
			        'position': 'absolute',
			        'right': '2px',
			        'top': '2px',
			        'backgroundColor': '#CCC',
			        'padding': '2px',
			        'font': '11px arial, helvetica',
			        'border': '1px solid #999',
			        'width': '400px',
			        'minHeight': '20px',
			        'opacity': '0.7',
			        'filter': 'alpha(opacity=70)',
			        'zIndex': '9999'
			    });
                traces.css
			    ({
			        'margin-top': '20px',
			        'border-top': '1px solid #666',
			        'minHeight': '10px'
			    });
                $("body").append(alertDiv);
            }
            traces.html(traces.html() + "<p>" + message + "</p>");
        }
    }
});

$.fn.extend({
	toggle:function(element)
	{
		$(this).click(function()
		{
			var hide = false;
			if($(element).css("display") != "none")
				{hide = true;}
			if(hide)
				{$(element).css("display", "none");}
			else
				{$(element).css("display", "");}
		});
	},
	toggableBy:function(toggler)
	{
		toggable = $(this);
		$(toggler).click(function()
		{
			toggable.toggle();
		});
	},	
	alpha: function()
	{
		if(arguments.length == 1)
		{
			if($.browser.msie)
				{$(this).css("filter", "alpha(opacity="+arguments[0]+")");}
			else
				{$(this).css("opacity", (arguments[0]/100));}
		}
		else
		{
			if($.browser.msie)
				{return $(this).css("filter");}
			else
			{
				try
				{
					return $(this).css("opacity");
				}
				catch(err)
				{
					return "100";
				}
			}
		}
	},	
	inspect: function()
	{
		var str = "";
		for ( var prop in $(this))
		{
			if(prop !== null)
			{
				str += "prop: " + prop + " = '" + $(this)[prop] + "'<br />";
			}
		}
		$.trace(str);
	},
	hasEvent:function(ev)
	{	 
	     if($(this).data('events') != 'undefined' && $(this).data('events') !== null)
	     {
		     if($(this).data('events')[ev] != 'undefined')
		     {return true;}
		     return false;
	     }
	     return false;
	},
	animations:{
		alpha:function(from, to, duration, callback)
		{			
			var currentalpha = from;
			
			var degrees = (parseFloat(((to - from) / duration)) * 40);
			if(degrees < 0)
				{degrees *= -1;}
			var ref = $(this);
			//$.trace(ref.attr("id"));
			var repeatID = $.repeat(function()
			{			
				if(from > to) //fade out
				{
					//$.trace($(this));
					if(currentalpha > to)
					{
						currentalpha -= parseInt(degrees,0);						
						ref.alpha(currentalpha);
					}
					else if(currentalpha <= to)
					{
						ref.alpha(to);
						window.clearInterval(repeatID);
						callback();
					}
				}
				else if(from <= to)
				{			
					if(currentAlpha < to)
					{	
						currentalpha += parseInt(degrees, 0);
						$(this).alpha(currentalpha);
					}
					if(currentalpha >= to)
					{
						$(this).alpha(to);
						callback();
						window.clearInterval(repeatID);
					}
				}
			}, 40);
		}
    }
//	position: function(pos)
//	{
//		var margin = 0;
//		if(arguments.length == 2)
//			{margin = arguments[1];}
//		$(this).each(function()
//		{
//			var parent = $(this).parent();
//			var parent_width = parent.width();
//			var parent_height = parent.height();
//			var element_width = $(this).width();
//			var element_height =  $(this).height();
//			var half_width = (parent_width/2) - (element_width/2);
//			var half_height = (parent_height/2) - (element_height/2);
//			parent.css("position","relative");
//			$(this).css("position","absolute");
//			$(this).css({'top':'', 'right':'', 'bottom':'','left':''});
//			if(pos == 'center'){$(this).css({'top': half_height, 'left':half_width});}
//			else if(pos == 'top'){$(this).css({'top':margin, 'left':half_width});}
//			else if(pos == 'topright'){$(this).css({'top':margin, 'right':margin});	}
//			else if(pos == 'right')	{$(this).css({'top':half_height, 'right':margin});}
//			else if(pos == 'bottomright'){$(this).css({'bottom':margin, 'right':margin});}
//			else if(pos == 'bottom'){$(this).css({'bottom':margin, 'left':half_width});}
//			else if(pos == 'bottomleft'){$(this).css({'bottom':margin, 'left':margin});}
//			else if(pos == 'left'){$(this).css({'top':half_height, 'left':margin});}
//			else if(pos == 'topleft'){$(this).css({'top':margin, 'left':margin});}
//		});			
//	}
	
});
