/**
 * @version $Id: loader.js 1156 2009-10-09 14:40:32Z 440hz $
 * @author 440hz
 */


jQuery.extend({

	AjaxCall : function() {

		$.fizzer_req = null;

		$('.tooltip').each( function (i,who) {

			title = $(who).attr('title');
			title = '<span id="tooltip-left"></span>'+
					'<span id="tooltip-center">'+title+'</span>'+
					'<span id="tooltip-right"></span>';
			$(who)
				.attr('title',title)
				.tooltip( {
					tip: '#icontip',
					_opacity: 1,
					_effect : 'fade'
				})
				.removeClass('tooltip')
			;

		});

		
//		$('.tooltip2').each( function (i, who) {
//			title = $(who).attr('title');
//			
//			title = '<div id="tooltip2-top"></div>'+
//					'<div id="tooltip2-center">'+title+'</div>'+
//					'<div id="tooltip2-bottom"></div>';
//			$(who)
//				.attr('title',title)
//				.tooltip( {
//					x: -10,
//					y: -100,				
//					tip: '#icontip',
//					_opacity: 1,
//					_effect : 'fade'
//				})
//				.removeClass('tooltip')
//			;
//		});

		$('.tooltip2').mouseover(function () {
			var offset = $(this).offset();
			offset.left = offset.left + 10;
			offset.top = offset.top - 110;

			var tooltip = '<div id="tt2" style="top:'+offset.top+'px; left:'+offset.left+'px; z-index:1000; position: absolute;"><div id="tooltip2-top"></div>'+
						  	  '<div id="tooltip2-center"></div>'+
						  '<div id="tooltip2-bottom"></div></div>';

            $.post('/ajax/shop/getGatewayInfo/'+$(this).attr('title'), {}, function (data) {
                if (data.fee == "Low") {
                    var clr = '4e8827';
                } else if (data.fee == "High" || data.fee == "Very High") {
                    var clr = '8f0400';
                } else {
                    var clr = 'b99106';
                }
                var html =  'Name: <strong>'+data.name+'</strong><br/>'+
                            'Transaction fee: <strong style="color: #'+clr+'">'+data.fee+'</strong><br/><br/>'+

                            '<strong>Product delivery time</strong><br/>'+
                            'First time buyer: <strong>'+data.delivery_first+'</strong><br/>'+
                            'Regular buyer: <strong>'+data.delivery_regular+'</strong><br/>'+
                            'Verification needed?: <strong>'+data.verif+'</strong><br/><br/>'+

                            'More info at <a href="'+data.url+'" target="_blank">'+data.url+'</a>';
                $('#tooltip2-center').html(html);
            }, 'json');

			//alert(offset.left + ', '+offset.top);
			if (!$('#tt2').length) {
				$(this).append(tooltip);
			}

		});
		
		$('.tooltip2').mouseout(function () {
			$('#tt2').remove();
		});
		
	
		

		$('.inputtooltip').each( function (i,who) {

			title = $(who).attr('title');
			title = '<span id="input-tooltip-left"></span>'+
					'<span id="input-tooltip-center">'+title+'</span>'+
					'<span id="input-tooltip-right"></span>';

			$(who)
				.attr('title',title)
				.tooltip( {
					tip: '#inputtip',
				    position: "center right",
					offset: [ 0 , 5],
					_effect : 'fade',
					events: {
					    def:       "mouseover,mouseout",                // default show/hide events for an element
					    input:     "focus mouseover,blur mouseout",                        // for all input elements
					    widget:    "focus,blur",    // select, checkbox, radio, button
					    tooltip:   "mouseover,mouseout"            // the tooltip element
					}
				})
				.removeClass('inputtooltip')
			;

		});


		$('.ajaxcall').unbind('click').click( function() {

			dropMenu();

			$(this).removeClass('ajaxcall');
			var url = $(this).attr('href');
			var rld = $(this).attr('reload');

			// IE compatibility PATCH
			// 440hz 12.08.2009
			url = url.replace(/http:\/\/[a-z\.]+/,'');
			var place = $(this).attr('place');

			place = place || '#fizzercenter';

			$(place).FizzerHREF(url, rld);


			layoutChanger();

			return false;
		});

		$('.popup').unbind('click').click( function() {

			hideContextMenu();

			$(this).removeClass('popup');

			var url		= $(this).attr('furl');
			var form	= $(this).attr('fform');
			if (typeof url != "string") {
				url = $(this).attr('href');
			}

			formdata = $('#'+form).formToArray();

			$.FizzerCheckBuffer();

			$('#'+$.fizzer_buffer).load(
				'/ajax'+url,
				formdata
			);

			return false;

		});

		$('.popupajax').unbind('click').click( function() {

			hideContextMenu();

			var title	= $(this).attr('ftitle');
			var url		= $(this).attr('furl');
			var form	= $(this).attr('fform');

			if (typeof url != "string") {
				url = $(this).attr('href');
				// IE compatibility PATCH
				url = url.replace(/http:\/\/[a-z\.]+/, '');
			}

			var w		= $(this).attr('fw');
			var h		= $(this).attr('fh');

			var param = {
				width	: w,
				height	: h
			};

			formdata = $('#'+form).formToArray();
			url = '/ajax'+url;

			$.FizzerDialogAJAX(title,url,formdata,{});

			return false;

		});

		$('.dialogclose').unbind('click').click( function() {

			hideContextMenu();

			$('#'+$.fizzer_dialog).dialog('destroy');
			return false;
		});
	},

	FizzerCheckBuffer : function() {

		if(!document.getElementById($.fizzer_buffer)) {
			$("body").append('<div id="'+$.fizzer_buffer+'" style="display:none"></div>');
		}

	},


	FizzerCheckDialog : function() {

		if(!document.getElementById($.fizzer_dialog)) {
			$("body").append('<div id="'+$.fizzer_dialog+'" title="Fizzer social network" style="display:none"><p style="margin-top: 10px;"><span id="'+$.fizzer_dialog_msg+'"></span></p></div>');
		}

	},

	FizzerDialog : function(title,text,param) {

		param = param || {};
		if(title == '')			title = 'Fizzer social network';

		$.FizzerCheckDialog();

		var defaults = {
			bgiframe		: true,
			modal			: true,
			draggable		: false,
			resizable		: false,
			position		: 'center',
			dialogClass		: 'alert',
			closeOnEscape	: true,
			title			: title,
			width			: 350,
			height			: 'auto',
			minHeight		: '150',
			minWidth		: '200',
			maxHeight		: '700',
			maxWidth		: '900',
			buttons			:
				{
					'Ok'	: function() { $('#'+$.fizzer_dialog).dialog('close').dialog('destroy'); }
				}
		};

		var options = $.extend	( defaults,	param );

		// already open
		// don't draw. only show content and reconfiguring
		if( $('#'+$.fizzer_dialog).dialog('isOpen') != true ) {
			$('#'+$.fizzer_dialog).dialog('destroy').dialog(options);
		}
		$('#'+$.fizzer_dialog_msg).html(text);
		$('#'+$.fizzer_dialog).dialog('option',options);
	},

	FizzerDialogAJAX : function(title,url,data,param) {

		$.FizzerCheckDialog();

		if(data == undefined) data = {};

		var defaults = {
			bgiframe		: true,
			modal			: true,
			draggable		: true,
			resizable		: false,
			position		: 'center',
			dialogClass		: 'alert',
			closeOnEscape	: true,
			title			: title,
			width			: 350,
			height			: 'auto',
			minHeight		: '150',
			minWidth		: '200',
			maxHeight		: '1200',
			maxWidth		: '900',
			buttons			:
				{
					'Abort'	: function() { $('#'+$.fizzer_dialog).dialog('destroy'); }
				}
		};

		var options = $.extend	( defaults, param );


		if( $('#'+$.fizzer_dialog).dialog('isOpen') == true ) {
			$('#'+$.fizzer_dialog).dialog('option',options).dialog('open');
		} else {
			$('#'+$.fizzer_dialog).dialog('destroy').dialog(options);
		}

		// for POST emulation
		// http://docs.jquery.com/Ajax/load#urldatacallback

		$('#'+$.fizzer_dialog_msg).html('<div style="text-align: center; line-height: 20px;"><img src="/skins/loader.gif" alt="" style="vertical-align: middle; margin-right: 10px;" /><strong>Loading, please wait...</strong></div>').load(url,data,function(responseText, textStatus, XMLHttpRequest) {
				$.AjaxCall();
				if (!$('.ui-dialog-buttonpane').is(':visible')) {
					$('.ui-dialog-content').css('-moz-border-radius', '0 0 6px 6px');
					$('.ui-dialog-content').css('border-bottom', '1px solid #7A828B');
				}
				//$.FizzerDialogModify();

		});
	},

	FizzerDialogModify : function(option) {

		if( option == undefined) option = {};

		var defaults = {
				bgiframe		: true,
				modal			: true,
				draggable		: true,
				resizeable		: false,
				position		: 'center',
				dialogClass		: 'alert',
				closeOnEscape	: true,
				height			: 'auto',
				maxHeight		: '700',
				maxWidth		: '900'
			};

		var o = $.extend	( defaults, option );

		$('#'+$.fizzer_dialog).dialog('option',o);
	},

	Anchor : function(module,method) {

		if(method == undefined)
			method = '';
		else
			method = '/' + method;
		var anchor = '#' + module + method;
		document.location.hash = anchor;
		return anchor;
	},

	AnchorFromUrl : function(url) {
		if (url.indexOf('.html?') > 0) {
			url = url.substr(0, url.indexOf('.html?'));
		}
		var anchor = url.substr(1).replace('.html','');
		$.fizzer_anchor = anchor;
		window.location.hash = anchor;
		return anchor;
	},

	AnchorClean : function() {
		document.location.hash = '';
	},

	AnchorTrac: function() {
		var anchor = $.getAnchor();
		if (anchor != $.fizzer_anchor) {
			$.fizzer_anchor = anchor;

			layoutChanger();

			$.reload('center');
		}
		setTimeout('$.AnchorTrac()', 200);
	},

	getAnchor : function() {

		anchor = document.location.hash;
		anchor = anchor.replace(/#([\/]+)?/,'');
		return anchor;
	},

	getAnchorArray : function() {

		anchor = document.location.hash;
		if( anchor == '' ) return {};
		anchor = anchor.replace('#','');
		a = anchor.split('/');
		return a;
	},

	getAnchorModule : function() {

		a = $.getAnchorArray();
		if( a[0] == undefined ) return '';
		return a[0];

	},

	getAnchorMethod : function() {

		a = $.getAnchorArray();
		if( a[1] == undefined ) return '';
		return a[1];

	},

	reload : function (param, callback) {
		param = param || "";
		if (param == 'center' || param == 'both') {
			var url = $.getAnchor();
			if (url == '') {
				url = 'home';
				$.Anchor(url)
			}
			$('#fizzercenter').FizzerLoader(url);
		}
		if (param == 'auth' || param == 'both') {
			$('#fizzerleft1').FizzerLoader('authorize', 'informer');
		}
		if (param == 'menu') {
			$('#fizzerleft2').FizzerLoader('menu', 'fullleft');
		}
	},

	updateTopMenu: function () {
		switch($.getAnchorModule()) {
			case 'bugs':
				return;
			case 'home':
			case '':
				module = 'home';
				break;
			case 'games':
				module = 'games';
				break;
			case 'events':
				module = 'events';
				break;
			case 'classmates':
				module = 'classmates';
				break;
			case 'shop':
				module = 'shop';
				break;
			case 'blogs':
				module = 'blogs';
				break;
			default:
				module = 'friends';
				break;
		}
		var $item = $('#ultopmenu li.active');
		if ($item.attr('id') != 'topmenu-'+module) {
			$item.removeClass('active');
			$('#topmenu-'+module).addClass('active');
		}
	},
	 blogVote: function (id, val) {
	 	var $obj = $('#blog-votes-'+id);
	 	if (!$obj.hasClass('blog-entry-voted')) {
		 	$.getJSON(
		 		'/ajax/blogs/vote/'+id+'/'+val+'.html',
		 		function (data) {
		 			if (data.error.length > 0) {
		 				$.FizzerDialog("Error", data.error);
		 			} else {
		 				$obj.addClass('blog-entry-voted');
		 				$obj.find('.rating').text(data.rating);
		 			}
		 		},
		 		'json'
		 	);
	 	}
	 }
});




(function($) {

	$.fizzer_dialog	= 'fizzer_dialog';
	$.fizzer_dialog_msg	= 'fizzer_dialog_msg';
	$.fizzer_buffer	= 'fizzer_buffer';
	$.fizzer_req = null;
	$.fizzer_anchor = $.getAnchor();

	$.fn.loadXMLHTTP = function( url, params, callback ) {
		if ( typeof url !== "string" )
			return this._load( url );




		var off = url.indexOf(" ");
		if ( off >= 0 ) {
			var selector = url.slice(off, url.length);
			url = url.slice(0, off);
		}

		// Default to a GET request
		var type = "GET";

		// If the second parameter was provided
		if ( params )
			// If it's a function
			if ( jQuery.isFunction( params ) ) {
				// We assume that it's the callback
				callback = params;
				params = null;

			// Otherwise, build a param string
			} else if( typeof params === "object" ) {
				params = jQuery.param( params );
				type = "POST";
			}

		var self = this;

		// Request the remote document
		return jQuery.ajax({
			url: url,
			type: type,
			dataType: "html",
			data: params,
			complete: function(res, status){
				// If successful, inject the HTML into all the matched elements
				if ( status == "success" || status == "notmodified" ) {
					// See if a selector was specified
					self.html( selector ?
						// Create a dummy div to hold the results
						jQuery("<div/>")
							// inject the contents of the document in, removing the scripts
							// to avoid any 'Permission Denied' errors in IE
							.append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))

							// Locate the specified elements
							.find(selector) :

						// If not, just inject the full result
						res.responseText );

					if( callback )
						self.each(callback);
				}
			}
		});
	};

	$.fn.FizzerLoaderFromAnchor = function() {
		module = $.getAnchorModule();
		method = $.getAnchorMethod();
		$(this).FizzerLoader(module,method);
	};

	$.fn.FizzerLoader = function(modul,method,options,callback) {

		method = method || '';

		$(this).load(
			'/ajax/'+modul+'/'+method+'.html',
			options,
			function() {
				$.AjaxCall();
				if ($.isFunction(callback)) callback();}
			);
	};

	$.fn.FizzerHREF = function(url, rld, options) {
		$('html').scrollTop(100);
		$(this).empty().append('<div style="text-align: center; margin-top: 50px; line-height: 20px;">'+
								'<img src="/skins/loader.gif" alt="" style="vertical-align: middle; margin-right: 10px;" \/>'+
								'<strong>Loading, please wait...<\/strong><\/div>');

		$.AnchorFromUrl(url);
		$.updateTopMenu();
		var ajax_url = '/ajax' + url;
		if ($.fizzer_req != null) {
			$.fizzer_req.abort();
		}
		$.fizzer_req = $(this).loadXMLHTTP(
			ajax_url,
			options,
			function() {
				_gaq.push(['_trackPageview', url]);
				$.AjaxCall();
				if (typeof rld != "undefined") {
					$('#fizzerleft2').FizzerLoader(rld, 'fullleft');
				}


				layoutChanger();

			}
		);

		return false;
	};

	$.fn.SwitchLayout = function (layouts, options) {

		if (layouts[0] != false) {
			var obj = $('#CSSLayoutId');
			obj.attr('href', obj.attr('href').replace(/[a-z\-]+\.css$/, layouts[0]));
		}

//		var anch = $.getAnchor();
//		//alert(anch);
//		if (anch != 'home') {
//			layouts[1] = 'layout_normal';
//		}

		url = '/ajax/layout/' + layouts[1];
		if ($.fizzer_req != null) {
			$.fizzer_req.abort();
		}
		$.fizzer_req = $(this).loadXMLHTTP(
			url,
			options,
			function() {
				$.AjaxCall();
			}
		);

		return false;
	};

})(jQuery);


function layoutChanger() {
	// layout changer

	if ($.getAnchorModule() == 'blogs' || $.getAnchorModule() == 'shop') {
		$('.left').hide();
		$('#wrap-top-content').css('padding', '0');
		$('#wrap-top-content').css('width', '100%');
		$('#fizzercenter').css('width', '100%');

	} else {
		$('.left').show();
		$('#wrap-top-content').css('padding', '15px 15px 0');
		$('#wrap-top-content').css('width', '928px');
		$('#fizzercenter').css('width', '695px');

	}

	if (($.getAnchorModule() != 'home') && ($.getAnchorModule() != 'anchor') && ($.getAnchorModule() != '')) {

		//if ($('#home-bl1').length && $('#home-bl1').is(':visible')) {

			$('#fizzerblogcomments').show();
			$('#home-bl1').hide();
			$('#home-bl2').hide();
			$('#home-bl3').hide();
			if ($('#with-auth-left').length) {
				$('#without-auth-left').hide();
			} else {
				$('#without-auth-left').show();
			}
		//}
	} else {
			$('#fizzerblogcomments').hide();
			$('#home-bl1').show();
			$('#home-bl2').show();
			$('#home-bl3').show();
			$('#without-auth-left').hide();
			$('#fizzercenter3').FizzerLoader('blogs', 'homeBlogsNoAuth');
	}
}

