
/**
 * With this patch jQuery can handle ajax responses without setting dataType.
 * Needed when response content-type is not known on forehand. 
 */
jQuery.extend({
	httpData: function( xhr, type, s ) {
		var ct = xhr.getResponseHeader("content-type"),
			xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
			script = type == "script" || !type && ct && ct.indexOf("script") >= 0,
			json = type == "json" || !type && ct && ct.indexOf("json") >= 0,
			data = xml ? xhr.responseXML : xhr.responseText;

		if ( xml && data.documentElement.tagName == "parsererror" )
			throw "parsererror";

		// Allow a pre-filtering function to sanitize the response
		// s != null is checked to keep backwards compatibility
		if( s && s.dataFilter )
			data = s.dataFilter( data, type );

		// If the type is "script", eval it in global context
		if ( script )
			jQuery.globalEval( data );

		// Get the JavaScript object, if JSON is used.
		if ( json )
			data = window["eval"]("(" + data + ")");
	    
	    return data;
	}
});

/**
 * Get the outerHtml
 */
jQuery.fn.outerHtml = function(s) {
	return (s)
	? this.before(s).remove()
	: jQuery("<p>").append(this.eq(0).clone()).html();
};

( function( $ ) 
		{
			$.fn.wresize = function( f ) 
			{
				version = '1.1';
				wresize = {fired: false, width: 0};

				function resizeOnce() 
				{
					if ( $.browser.msie )
					{
						if ( ! wresize.fired )
						{
							wresize.fired = true;
						}
						else 
						{
							var version = parseInt( $.browser.version, 10 );
							wresize.fired = false;
							if ( version < 7 )
							{
								return false;
							}
							else if ( version == 7 )
							{
								//a vertical resize is fired once, an horizontal resize twice
								var width = $( window ).width();
								if ( width != wresize.width )
								{
									wresize.width = width;
									return false;
								}
							}
						}
					}

					return true;
				}

				function handleWResize( e ) 
				{
					if ( resizeOnce() )
					{
						return f.apply(this, [e]);
					}
				}

				this.each( function() 
				{
					if ( this == window )
					{
						$( this ).resize( handleWResize );
					}
					else
					{
						$( this ).resize( f );
					}
				} );

				return this;
			};

		} ) ( jQuery );


jQuery.fn.columnify = function(options) {

    var defaults = { 
        cols: 3,
        tag: 'label'
    }
    var settings = $.extend(defaults, options);

    var tags = $(this).find(settings.tag);
    
    if (tags && tags.length > 0) {
	    var rows = Math.floor(tags.length / settings.cols);
	    var extra = tags.length % settings.cols;
	
	    var begin = 0;
	    var end = 0;
	    var columns = {};
	    for(var i = 0; i < settings.cols; i++) {
	        var x = (i < extra) ? rows + 1 : rows;
	        columns[i] = tags.slice(begin, begin + x);
	        begin += x;        
	    } 
	    var html = '<div class="cols">';
	    $.each(columns, function(n, val){
	        html += '<div class="col' + n + '">';
	        val.each(function(){
	            html += $(this).outerHtml() + '<br />'
	        });
	        html += '</div>';
	    });
	    html += '<div class="clear"></div></div>';
	    
	    $(this).html(html);
	    
	    return $(this);
    }
}

jQuery.fn.zebra = function(options) {

	var defaults = {
	    element: 'div.item',
	    itemlink: true,
	    skipFirst: false
	}
	var opts = $.extend(defaults, options);

	$(this).addClass('zebra');
	
	$(this).find(opts.element + ':visible' + (opts.skipFirst ? ':not(:first)' : '') + ':odd').removeClass('odd').removeClass('even').addClass('odd');
	$(this).find(opts.element + ':visible' + (opts.skipFirst ? ':not(:first)' : '') + ':even').removeClass('odd').removeClass('even').addClass('even');

//	var odd = { backgroundColor: '#f5f5f5' }
//	var even = { backgroundColor: '#ffffff' }
//	
//	$(this).find(opts.element + ':visible' + (opts.skipFirst ? ':not(:first)' : '') + ':odd').animate(odd);
//	$(this).find(opts.element + ':visible' + (opts.skipFirst ? ':not(:first)' : '') + ':even').animate(even);
	
	$(this).find(opts.element + (opts.skipFirst ? ':not(:first)' : '')).hover(
		function() {
	        $(this).addClass('hover');
	    },
	    function() {
	        $(this).removeClass('hover');
	    }
	);
	
//	if (opts.itemlink) {
//		$(this).find(opts.element).live('click', function() {
//			var lnk = $(this).find("a.itemlink").attr("href");
//			if (lnk) {
//				document.location.href = lnk;
//			}
//		});
//	}

	//$(this).find(opts.element).die('click', itemlink());
	if (opts.itemlink) {
		$(this).find(opts.element).live('click', function(){
			var lnk = $(this).find("a.itemlink").attr("href");
			if (lnk) {
				document.location.href = lnk;
			}
		});
	}
	
//	$(this).find("div.item:odd").addClass("zebra");
//	
//	$(this).find("div.item").hover(
//		function() {
//            $(this).addClass('hover');
//        },
//        function() {
//            $(this).removeClass('hover');
//        }
//    );
//	
//	$(this).find("div.item").live('click', function() {
//		var lnk = $(this).find("a.itemlink").attr("href");
//		if (lnk) {
//			document.location.href = lnk;
//		}
//	});
	
	return $(this);
}


jQuery.fn.getAds = function(options) {
    
    var defaults = {
        width: 0,
        height: 0,
        count: 1,
        type: 'ad',
        tag: null,
        replace: 'div.image',
        removeWhenEmtpy: true
    }
    var opts = $.extend(defaults, options);

    $(this).each(function(){
        var spot = $(this);
        spot.hide(0);
        //spot.find('div.image').css({ opacity: 0 });
        $.ajax({
            url: '/ad/show',
            type: 'post',
            dataType: 'html',
            data: 'width=' + opts.width + '&height=' + opts.height + '&count=' + opts.count + '&type=' + opts.type + '&tag=' + (opts.tag ? opts.tag : ''),
            success: function(data){
                if (data.length > 0) {
                    if (opts.replace && spot.find(opts.replace).length > 0) {
                        spot.find(opts.replace).replaceWith(data);
                    } else {
                    	spot.append(data);
                    }
                    //spot.find('div.image').animate({ opacity: 1}, 2000);
                    //spot.find('div.image').fadeIn(5000);
                    spot.slideDown();
                } else {
                    if (opts.removeWhenEmpty) {
                    	spot.remove();
                    } else if (opts.replace) {
                		spot.find(opts.replace).remove();
                	} else {
                		spot.remove();
                	}
                }
                
            }
        });
    });
    
//    var spot = $(this);
//    $.ajax({
//        url: '/ad/show',
//        type: 'post',
//        dataType: 'html',
//        data: 'width=' + opts.width + '&height=' + opts.height + '&count=' + opts.count + '&type=' + opts.type,
//        success: function(data){
//            if (data.length > 0) {
//                if (opts.replace && spot.find(opts.replace).length > 0) {
//                    spot.find(opts.replace).replaceWith(data);
//                } else {
//                	spot.append(data);
//                }
//            } else {
//                if (opts.removeWhenEmpty) {
//                	spot.remove();
//                } else if ($opts.replace) {
//            		spot.find(opts.replace).remove();
//            	} else {
//            		spot.remove();
//            	}
//            }
//            
//        }
//    });
}

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


(function($) {
	$.fn.koPopup = function(settings) {
		var config = {
			title: '',
			modal: true,
			autoOpen: false,
			resizable: false,
			draggable: true,
			minWidth: 600,
			maxWidth: 600,
			width: 600,
			buttons: {}
		};
		
		if (settings) $.extend(config, settings);
		
		if ($('div.func-popup').length == 0) {
			$('body').append('<div class="func-popup"></div>');
		}
		// Hide popup
		$('div.func-popup').hide();
		$('div.func-popup').dialog(config);
		
//		this.each(function() {
//			// element-specific code here
//		});
		return this;
	};
	
	$.fn.koPopup.show = function(title, html) {
		$('div.func-popup')
			. html(html)
			. dialog('option', 'title', title)
			;
		$('div.func-popup').dialog('open');
	}
})(jQuery);
