﻿/**
 * console.log helper
 */
function cl(o) {
	return false;
    try { console.log.apply(console, arguments) } catch(e) {}
}


/**
 * Updates the footer after login
 */
var updateFooter = function() {
	$('#acc-login').replaceWith('<a href="/profiles/' + account.user.username + '" id="acc-profile">' + account.user.name + '</a>');
	$('#acc-register').replaceWith('<a id="acc-logout" onclick="account.logout();">logout</a>');
}


/**
 * Reload page after login
 */
var reloadPage = function() {
	window.location.reload(true);
}



/**
 * swfupload image uploaderp
 */
var ImageUploader = (function() {
	var uploader;
	var settings = {
		flash_url : "/_res/libs/swfupload/swfupload.swf",
		upload_url: "/_ajax/profile/avatar/",
		//post_params: {"PHPSESSID" : ""},
		file_post_name: "profile[avatar]",
		file_size_limit: "1 MB",
		file_types: "*.jpg;*.png;*.gif",
		file_types_description: "Images",
		file_upload_limit: 0,
		file_queue_limit: 1,
		custom_settings : {
			progressTarget : "fsUploadProgress",
			cancelButtonId : "btnCancel"
		},
		debug: false,
		
		// Button settings
		//button_image_url: "http://demo.swfupload.org/v220/simpledemo/images/TestImageNoText_65x29.png",
		button_width: "65",
		button_height: "29",
		button_placeholder_id: "pictureAvatarChose",
		button_text: 'click pentru a alege poza',
		button_text_style: ".theFont { font-size: 16;  }",
		button_text_left_padding: 12,
		button_text_top_padding: 7,
		button_cursor : SWFUpload.CURSOR.HAND,
		button_window_mode : SWFUpload.WINDOW_MODE.TRANSPARENT,

		// The event handler functions are defined in handlers.js
		//file_queued_handler : SWFUpload.queue.fileQueued,
		//file_queue_error_handler : SWFUpload.queue.fileQueueError,
		file_dialog_complete_handler : function() {
			//cl('starting upload');
			uploader.setPostParams({
				'__CMS_USER': $.cookie('__CMS_USER')
			});
			uploader.startUpload();
		},
		//upload_start_handler : SWFUpload.queue.uploadStartHandler,
		//upload_progress_handler : SWFUpload.queue.uploadProgress,
		//upload_error_handler : SWFUpload.queue.uploadError,
		//upload_success_handler : SWFUpload.queue.uploadSuccess,
		upload_success_handler: function(file, data, receivedResponse) {
			var response = $.parseJSON(data);
			if(response.success) {
				$('#profileAvatar p.picture').first().replaceWith($(response.html).find('p.picture'));
				$('#pictureEditClose').trigger('click');
			}
		},
		upload_complete_handler : function(file) {
		}
		//queue_complete_handler : SWFUpload.queue.queueComplete	// Queue plugin event
	};
	
	return {
		initialize: function() {
			uploader = new SWFUpload(settings);
		}
	}
})();


/**
 * Fancyloader
 * @description takes an element(usually an anchor) and uses his href attribute to load a particular html resource
 */
(function() {
	$.fn.fancyLoader = function(options) {
		var $this = $(this);
		var opts = $.extend($.fn.fancyLoader.defaults, options);
		opts.manualTrigger ? manualLoad($this) : initTriggers($this)
	}
	
	var doAjax = function(url, cb) {
		$.ajax({
			cache: false,
			type: 'GET',
			url: url,
			success: function(res, status) {
				if(cb)
					cb.call(this, res);
			}
		});
	}
	
	var loadResource = function(er, $obj) {
		if((er && er.length < 1) || !er || (er && er === '#')) {
			throw new Error('Unable to determine the anchor href attribute!');
		}
		doAjax(er, function(res) {
			var resPage = res;
			if($.browser.msie) var fancyContent = res;
			else var fancyContent = $(res).find('#fancy').html() || res;
			$($.fn.fancyLoader.defaults.to).show().html(fancyContent).after(function() {
				afterCallback();
				buildPagination();
				if($.fn.fancyLoader.defaults.addHash)
					addHash(er);
			});
		});
	}
	
	/**
	 * Adds the current clicked fancybox resource href to the location.hash
	 */
	var addHash = function(resource) {
		var pathname = window.location.pathname;
		window.location.hash = '/' + resource.replace(pathname, '');
	}
	
	var manualLoad = function($obj) {
		var er = $($obj).attr('href');
		loadResource(er, $obj);
	}
	
	var initTriggers = function($obj) {
		$obj.live('click', function(e) {
			e.preventDefault();
			//if($(this).hasClass('fancy-open')) {
			if(!$(this).hasClass('ignore')) {
				var er = $(this).attr('href');
				loadResource(er, $obj);
			}
		});
		
		$('#fancy').find('.close-fancy').live('click', function(e) {
			e.preventDefault();
			$($.fn.fancyLoader.defaults.to).hide().html();
		});
	}
	
	var afterCallback = function(ctx, options) {
		var context = ctx || this;
		try {
			$.fn.fancyLoader.defaults.afterLoad.call(context);
		} catch(e) {}
	}
	
	$.fn.fancyLoader.defaults = {
		// this should be an element or an array of elements representing the container which holds the ajax content
		to: null,
		// set TRUE if the elements are binded to live() and the click event already been triggered
		manualTrigger: false,
		// adds the current link hred to the location.hash
		addHash: false,
		// callbacks
		beforeLoad: null,
		afterLoad: null
	}
})(jQuery);


/**
 * Headerp menu
 */
var headerMenu = (function() {
	var defaultContainer = '#header-menu',
		submenuContainer = 'ul.submenu',
		defaultTimeoutVal = 300,
		currentTimeout = null,
		current = null,
		$triggers = null;
	
	var initEvents = function() {
		$triggers.mouseover(function() {
			//cl('over')
			$(defaultContainer).find(submenuContainer).hide();
			current = this;
			showSubmenu();
		});
		
		$triggers.mouseout(function() {
			//cl('out')
			current = null;
			closeSubmenu();
		});
		
		$(defaultContainer).find(submenuContainer).mouseenter(function() {
			clearTimeout(currentTimeout);
		}).mouseleave(function() {
			closeSubmenu();
		})
	}
	
	var showSubmenu = function() {
		//cl('show')
		var $submenuElem = $(current).next('ul');
		clearTimeout(currentTimeout);
		$submenuElem.show();
	}
	
	var closeSubmenu = function() {
		currentTimeout = setTimeout(function() {
			$(defaultContainer).find(submenuContainer).hide();
		}, defaultTimeoutVal);
	}
	
	var initTriggers = function() {
		$triggers = $(defaultContainer).find(submenuContainer).prev('a');
	}
	
	return {
		initialize: function() {
			initTriggers();
			initEvents();
		}
	}
})();


/**
 * dom ready
 */
$(function() {
	// all the links(except .ignore) will load into the fancybox
	// UNCOMMENT THIS IN PRODUCTION AND ADD .ignore TO ALL THE ~STATIC ANCHORS
	$('#fancy').find("a:not('.ignore')").fancyLoader({
		to: '#fancy'
	});
	
	ImageUploader.initialize();
	forms._widgetize();
	
	account.afterLogin.push(updateFooter);
	account.afterLogin.push(reloadPage);
	
    $('.ac_city').each(function(idx,item) {
		var c_ac = $(this);
		var judet;
		c_ac.autocomplete({
			minLength: 2
			,delay:10
			,appendTo:this.parentNode
			,select: function( event, ui ) {
				$(this).val(ui.item.label);
				$(this).next('.ac_cityid').val(ui.item.id);
			}
			,source : function(request, response) {
				/**
                 * @this : Object, not Element, not jQuery object
                 */
				
				var judet = $('.ac_countyid').eq(idx).val();
                
				var data = {
					action : 'getCity',
					j:judet,
					l:request.term
				}
				$.ajax({
					type:'POST',
					url:'/_ajax/',
					data: data,
					dataType: "json",
					success: function(res, status) {
						response(res["data"]);
					}
				});
			}
		});
	});
	
	
	/**
	 * Forms Birthday fields
	 */
	$('form div[rel="birthdate"]').each(function(){
		var element = $(this);
		var day = element.find('.d_day').val();
		var month = element.find('.d_month').val();
		var year = element.find('.d_year').val();
		var field = element.find('input');

		element.find('select.d_day').change(function(){
			day = $(this).val();	
			field.val(year+'-'+month+'-'+day);
		});
		element.find('select.d_month').change(function(){
			month = $(this).val();
			field.val(year+'-'+month+'-'+day);
		});
		element.find('select.d_year').change(function(){
			year = $(this).val();
			field.val(year+'-'+month+'-'+day);
		});
	   
	});
	
	
	/**
	 * Profile update form
	 */
	 
	$("#pictureEditClose").click(function(e){
		$("div.pictureForm").addClass("invisible");
		e.preventDefault();
	});
	
	$("#pictureEditShow").click(function(e){
		$("div.pictureForm").removeClass("invisible");
		e.preventDefault();
	});
	
	$('#basicInfoForm').submit(function(evt) {
		form = $(this);
			var data = form.serialize();
			var url = form.attr('action');
			$.ajax({
				type: 'POST',
				url: url,
				dataType: 'json',
				data: data,
				beforeSend:function(xhr,settings){
					//cleanup previous errors if any
					form.find('.error').remove();
					form.find('.hasError').removeClass('hasError');
				},
				success: function(response,status,xhr){
					if(response.success === true){
						$('#basicInfoProfile').replaceWith(response.html);
						$('#basicInfoForm').toggle('hide');
						$('#profileEditShow').show();
						$('#basicInfoProfile').show();
						$('p.pictureModify').show();
					} else {
						$.each(response.errors,function(idx,err){
							var errContainer = $(form).find('div.element[rel='+idx+']');
							errContainer.addClass('hasError');
							$('<p/>').html(err).addClass('error').appendTo(errContainer);
						});
					}
				}
			});
			return false;
		
	});
	
	
	$('#profileEditClose').click(function(evt) {
		evt.preventDefault();
		$('#basicInfoForm').toggle('hide');
		$('#profileEditShow').show();
		$('#basicInfoProfile').show()
		$('p.pictureModify').show();
	});


	$('#profileEditShow').click(function(evt) {
		evt.preventDefault();
		$(this).hide();
		$('#basicInfoForm').toggle('show');
		$('#basicInfoProfile').toggle('hide');
		$('p.pictureModify').hide();
	});
	
	
	/**
    * See more header drop down
    */
    $('#see-more').click(function() {
        $('#global').slideToggle(250);
		return false;
    });
    

	/** 
	* Sustine Echipa
	*/
	if($('#sustineEchipa').size()){
		$('#sustineEchipaShow').click(function (evt){
			evt.preventDefault();
			$('#sustineEchipa p.actions').hide();
			$('#sustineEchipaForm').show();
		});
		$('#sustineEchipaHide').click(function (evt){
			evt.preventDefault();
			$('#sustineEchipa p.actions').show();
			$('#sustineEchipaForm').hide();
		});

		$('#sustineEchipaForm').submit(function(evt) {
			evt.preventDefault();
			form = $(this);
			var data = form.serialize();
			var url = form.attr('action');
			$.ajax({
				type: 'POST',
				url: url,
				dataType: 'json',
				data: data,
				beforeSend:function(xhr,settings){
					//cleanup previous errors if any
					form.find('.error').remove();
					form.find('.hasError').removeClass('hasError');
				},
				success: function(response,status,xhr){
					if(response.success === true){
						$('#sustineEchipaForm').replaceWith(response.html);
					} else {
						$.each(response.errors,function(idx,err){
							var errContainer = $(form).find('div.element[rel='+idx+']');
							errContainer.addClass('hasError');
							$('<p/>').html(err).addClass('error').appendTo(errContainer);
						});
					}
				}
			});
			return false;
		});
	}
	/** -- */
	
	
	/** 
	* Pareri fotbal
	*/
	if($('#pareriFotbal').size()){
		$('#pareriFotbalShow').click(function (evt){
			evt.preventDefault();
			$('#pareriFotbal p.actions').hide();
			$('#pareriFotbalForm').show();
		});
		$('#pareriFotbalHide').click(function (evt){
			evt.preventDefault();
			$('#pareriFotbal p.actions').show();
			$('#pareriFotbalForm').hide();
		});

		$('#pareriFotbalForm').submit(function(evt) {
			evt.preventDefault();
			form = $(this);
			var data = form.serialize();
			var url = form.attr('action');
			$.ajax({
				type: 'POST',
				url: url,
				dataType: 'json',
				data: data,
				beforeSend:function(xhr,settings){
					//cleanup previous errors if any
					form.find('.error').remove();
					form.find('.hasError').removeClass('hasError');
				},
				success: function(response,status,xhr){
					if(response.success === true){
						$('#pareriFotbalForm').replaceWith(response.html);
					} else {
						$.each(response.errors,function(idx,err){
							var errContainer = $(form).find('div.element[rel='+idx+']');
							errContainer.addClass('hasError');
							$('<p/>').html(err).addClass('error').appendTo(errContainer);
						});
					}
				}
			});
			return false;
		});
	}
	/** -- */

	/** 
	* Motive Voie Buna
	*/
	if($('#motiveVoiebuna').size()){
		$('#motiveVoiebunaShow').click(function (evt){
			evt.preventDefault();
			$('#motiveVoiebuna p.actions').hide();
			$('#motiveVoiebunaForm').show();
		});
		$('#motiveVoiebunaHide').click(function (evt){
			evt.preventDefault();
			$('#motiveVoiebuna p.actions').show();
			$('#motiveVoiebunaForm').hide();
		});

		$('#motiveVoiebunaForm').submit(function(evt) {
			evt.preventDefault();
			form = $(this);
			var data = form.serialize();
			var url = form.attr('action');
			$.ajax({
				type: 'POST',
				url: url,
				dataType: 'json',
				data: data,
				beforeSend:function(xhr,settings){
					//cleanup previous errors if any
					form.find('.error').remove();
					form.find('.hasError').removeClass('hasError');
				},
				success: function(response,status,xhr){
					if(response.success === true){
						$('#motiveVoiebunaForm').replaceWith(response.html);
					} else {
						$.each(response.errors,function(idx,err){
							var errContainer = $(form).find('div.element[rel='+idx+']');
							errContainer.addClass('hasError');
							$('<p/>').html(err).addClass('error').appendTo(errContainer);
						});
					}
				}
			});
			return false;
		});
	}
	/** -- */


	/** 
	* Contact Form
	*/
	if($('#contactForm').size()){
		$('#contactForm').submit(function(evt) {
			evt.preventDefault();
			form = $(this);
			var data = form.serialize();
			var url = form.attr('action');
			$.ajax({
				type: 'POST',
				url: url,
				dataType: 'json',
				data: data,
				beforeSend:function(xhr,settings){
					//cleanup previous errors if any
					form.find('.error').remove();
					form.find('.hasError').removeClass('hasError');
				},
				success: function(response,status,xhr){
					if(response.success === true){
						$('#contactForm').replaceWith(response.html);
					} else {
						$.each(response.errors,function(idx,err){
							var errContainer = $(form).find('div.element[rel='+idx+']');
							errContainer.addClass('hasError');
							$('<p/>').html(err).addClass('error').appendTo(errContainer);
						});
					}
				}
			});
			return false;
		});
	}
	/** -- */

	/** 
	* Criterii Voie Buna
	*/
	if($('#criteriiVoiebuna').size()){
		$('#criteriiVoiebunaEdit').submit(function(evt) {
			evt.preventDefault();
			form = $(this);
			var data = form.serialize();
			var url = form.attr('action');
			$.ajax({
				type: 'POST',
				url: url,
				dataType: 'json',
				data: data,
				beforeSend:function(xhr,settings){
					//cleanup previous errors if any
					form.find('.error').remove();
					form.find('.hasError').removeClass('hasError');
				},
				success: function(response,status,xhr){
					if(response.success === true){
						$('#criteriiVoiebunaEdit').replaceWith(response.html);
					} else {
						$.each(response.errors,function(idx,err){
							var errContainer = $(form).find('div.element[rel='+idx+']');
							errContainer.addClass('hasError');
							$('<p/>').html(err).addClass('error').appendTo(errContainer);
						});
					}
				}
			});
			return false;
		});
	}
	/** -- */



	headerMenu.initialize();

});






$(function(){
	$('.ogUrl').attr('content',document.location);
	$('.ogTitle').attr('content',document.title);
});

$(function() {
	if($('.gallery a').length>0) {
		if(!($(".gallery").parents("#media-gallery").length>0 && $(".gallery").parents("#media-gallery").hasClass('ignore'))) $('.gallery a').lightBox({fixedNavigation:true});
	}
});


/*********** fotbal game nag ****************/
$(function() {
	$("#close-footballGameNag").live('click',function(){
		$.cookie('footballGame', '1', { path:'/', expires:7 });
		$("#footballGameNag").hide();
		return false;
	});
	//console.log(window.location.pathname);
    if($.cookie('footballGame') == null && $.cookie('rememberAge') && window.location.pathname.search('/joc-fotbal/')==-1) {
        $("#footballGameNag").show();
		//alert('joaca-te si tu');
	}
});


