// var events este folosita in views/events/index.html pt a crea un array cu evenimente, este folosit pt calendarul cu evenimente
var events= new Array();
var eventSelected = '';
//call this function to reload all banners on the page
function rotateBanners()
{
	//reload all iframes on the page
	$('.banner').each(function() {
	 this.contentWindow.location.reload(true);
	});
}

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;
    }
};
// Read the coockie for show login html in the header
$(document).ready(function(){

	var nameId = 'phpbb3_u' + "=";
	var nameUser = 'phpbb3_un' + "=";
	var coockie = document.cookie;0
	if ( coockie.match(nameId) == null )
	{
		return false;
	}
	var cookieElems = document.cookie.split(';');
	for(var i=0;i < cookieElems.length;i++) 
	{
		var values = $.trim(cookieElems[i]);
		if (values.match(nameId) == nameId) 
		{
			var userId =  parseInt(values.substring(nameId.length,values.length));
		}
		if (values.match(nameUser) == nameUser) 
		{
			var userName =  values.substring(nameUser.length,values.length);
		}
	}
	var htmlLogin = '<form name="loginform" id="loginform" method="post" action="" style="display:inline;">'
		htmlLogin += '<input type="hidden" name="_logout">'
		htmlLogin += '</form>'
		htmlLogin += '<a href="/utilizator/">Bine ai venit, '+userName+' </a>'
		htmlLogin += '<a href="/utilizator/">[ pagina mea ]</a>'
		htmlLogin += '<a href="/utilizator/'+userName+'-'+userId+'/editeaza.html">[ editare profil ]</a>'
		htmlLogin += '<a href="#" onclick=loginform.submit();>[ logout ]</a>'
	$('.login').html(htmlLogin);
});
App = {
	pageName : '',
	initAutocomplete : 	function(parent) {
			var	parent = parent || $('body');
			$('.autocompleteTxt', parent).each(function() 
			{
				var _autocomplete = $(this);
				var _hiddenField = _autocomplete.next();
				var first = true;
				_autocomplete.keydown(function()
				{
					if (first)
					{
						_hiddenField.val('');
						first = false;
						setTimeout(function()
						{
							first = true;
						}, 500);
					}
				});
				_autocomplete.blur(function()
				{
					setTimeout(function()
					{
						if (_hiddenField.val() == '' && _autocomplete.val() != '')
						{
							_autocomplete.val('');
							_autocomplete.focus();
							
							alert('Selecteaza o optiune din lista sau introdu un alt sir de cautare');
						}
					},300);
					
				});				
				
				var url = '/index.php?module=Ajax&action=autoComplete&type=' + _autocomplete.attr('_type');
				_autocomplete.autocomplete(url, {
					minChars : 2,
					autoFill : true,
					formatItem: function(row, i, max) {
						return row[0];
					},
					formatResult: function(row) {
						return row[0];
					}
					
				}).result(function(event, item) 
				{					
					var _this = $(this);										
					_this.next().val(item[1]);
				});
		});
	}
};

App.initors = {};

App.initors.viewPhoto = function()
{
	var renameBtn = $('#renamePhoto');
	if (renameBtn.length == 0)
	{
		return false;
	}
	var _parent = renameBtn.parent();

	var photoTitleContainer = $('span', _parent);
	var photoTitle = photoTitleContainer.text();
	var photoId = renameBtn.attr('photoId');	
	
	var showInputTxt = true;

	var renamePhoto = function()
	{

	}
	renameBtn.click(function()
	{
		if (showInputTxt)
		{
			photoTitle = photoTitleContainer.text();
			photoTitleContainer.html('<input id="photoTitleInput" type="text" value="' + photoTitle +'" />');

			renameBtn.text('Salveaza');
			showInputTxt = false;
		}
		else
		{
			var inputTxt = $('#photoTitleInput');
			var newPhotoTitle = inputTxt.val();
			$.post(window.location.href, 
				{ 
					'imageTitle' : newPhotoTitle,
					'imageId' : photoId
				},
						
				function(data)
				{
					if (data.error == false)
					{
						photoTitleContainer.html(newPhotoTitle);
						renameBtn.text('Redenumeste');
						showInputTxt = true;
						alert(data.message);
					}
					else
					{
						inputTxt.val(photoTitle);
						alert(data.message);
					}
				}, 

				'json'
			);

		}

	});
}
App.initors.settings = function()
{
    $(document).ready(function(){
        var nrCheckboxOn = $("input[id^=alert_]:checked").length;
        var nrCheckbox = $("input[id^=alert_]").length;
        if ( nrCheckboxOn == nrCheckbox )
        {
            $('#select_all').attr('checked','checked');
        }
    });
     $("input[id^=alert_]").change(function()
	{
        var nrCheckboxOn = $("input[id^=alert_]:checked").length;
        var nrCheckbox = $("input[id^=alert_]").length;
        if ( nrCheckboxOn == nrCheckbox )
        {
            $('#select_all').attr('checked','checked');
        }
        else
        {
            $('#select_all').attr('checked','');
        }
		return false;
	});
    $('#select_all').change(function()
	{
        var nrCheckboxOn = $("input[id^=alert_]:checked").length;
        var nrCheckbox = $("input[id^=alert_]").length;
        if ( nrCheckboxOn != nrCheckbox )
        {
            $("input[id^=alert_]").attr('checked','checked');
        }
        else
        {
            $("input[id^=alert_]").attr('checked','');
            $('#select_all').attr('checked','');
        }
		return false;
	});
}
/* View foto la dimensiuni normale in pag de stire  */

App.initors.findFriends = function()
{
	$('.inviteFriendLnk').click(function()
	{
		$.popup('Invite');
		var _this = $(this);
		var friendId = _this.attr('friend_id');
		$('#friendId').val(friendId);
		
		return false;
	});
}
App.initors.searchUsers = function()
{
	$('.inviteUserLnk').click(function()
	{
		$.popup('InviteUser');
		var _this = $(this);
		var friendId = _this.attr('friend_id');
		$('#friendId').val(friendId);
		
		return false;
	});
}
App.initors.addBlog = function()
{
	$('.addBlog').click(function()
	{
		$.popup('blogAdd');
		return false;
	});
}


App.initors.sendMessage = function()
{	

	$('.addDest, .removeDest').live('click', function()
	{
		var _this = $(this);
		var _parent = _this.parent();
		if (_this.hasClass('removeDest'))
		{
			_parent.remove();
		}
		else
		{
			if ($('.autocompleteId', _parent).val() == '')
			{
				if ($('.autocompleteTxt', _parent).val() != '')
				{
					alert('Acest destinatar nu exista');
					return false;
				}
				else
				{
					alert('Nu ati introdus destinatarul');
					return false;
				}
			}
			var container = _parent.parent();
			var clone = _parent.clone();
			$('input', clone).val('');
			App.initAutocomplete(clone);

			container.prepend(clone);
			_this.text('Sterge destinatar');
			_this.addClass('removeDest').removeClass('.addDest');;
		}
	});

}

jQuery().ready(function()
{
		Gallery.init();
		VideoGallery.init();
		Fanclubs.init();
		App.initAutocomplete();
        
		if (typeof App.initors[App.pageName] == 'function') {
			App.initors[App.pageName]();
		}
		if (0 < $(".acParent").length)
		{
			$(".acParent").change(function(){
				enableCountryCities ($(this));
			});
			enableCountryCities ($(".acParent"));
		}
		if (0 < $(".acLocationParent").length)
		{
			$(".acLocationParent").change(function(){
				enableCountyCities ($(this));
			});
			enableCountyCities ($(".acLocationParent"));
		}
		if (0 < $("#calendar").length)
		{
			if ( eventSelected.length > 0 )
			{
				var temp = new Array();
				temp = eventSelected.split('-');
				$('#calendar').calendarWidget({
					month:(temp[1]-1),
					year:temp[2],
					events:events,
					eventSelected:eventSelected
				});
			}else{
				$('#calendar').calendarWidget({
					events:events
				});				
			}
		}
		if (0 < $(".addNewMultiselect a").length)
		{
			$(".addNewMultiselect a").click(function(){
				var _type = $(this).attr('_type');
				var selector = "select.defaultMultiselect."+ _type;
				if (0 < $(selector).length)
				{
					var _this = $(".addNewMultiselect."+ _type);
					var id = Math.floor(Math.random()*10000000000);
					_this.before('<span id="ss'+ id +'"><a href="javascript: void(0);" onClick="javascript: removeMultiselect(\'ss'+ id +'\')"> Sterge</a></span>');
					var _span = $('span:last', _this.parent());
					_span.prepend($("select.defaultMultiselect."+ $(this).attr('_type')).clone().removeClass('defaultMultiselect').attr('selectedIndex', 0));
				}
			});
		}
		if (0 < $("#evenimente_viitoare").length || 0 < $("#nu_rata").length)
		{
			if (0 < $("#evenimente_viitoare").length)
			{
				var _parent = $('#evenimente_viitoare');
			}
			else if (0 < $("#nu_rata").length)
			{
				var _parent = $('#nu_rata');
			}
			var _links = $('div.title a', _parent);
			var _events = $('.event', _parent);

			_links.each(function(i)
			{
				var _link = $(this);
				_link.click(function()
				{
					if (_link.parent().next().hasClass('open'))
					{
						return true;
					}
					$('.open').slideUp(400, function() {
						_events.removeClass('open');
						_events.eq(i).addClass('open').slideDown(400);
					});
					return false;
				});
			});
		}
		//binding for overlay login, login using ajax, not finished
		/*$('#btnLogin').click(function() 
		{
			$.ajax({
			  type: "POST",
			  url: "/?module=Ajax&action=login",
			  data:'&username=' + $('#username').val() + '&password=' + $('#password').val(),
			  success: function(msg)
			  {
					alert( "Data Saved: " + msg );
			  }
			});
			return false;
		});*/
});
function enableCountryCities (e)
{
	if ('romania' == e.val())
	{
		$("#subCounty").css('display', 'block');
		$("#subCounty #county").attr('disabled', false);
	}
	else
	{
		var location = $(".acParent").attr('_location');
		$('#acLocation').html('<option value="">Alege localitatea</option>');
		if ('undefined' != typeof (cities))
		{
			for ( key in cities[e.val()] )
			{
				$('#acLocation').append('<option val="' + cities[e.val()][key] + '"'+ (location == cities[e.val()][key] ? ' selected' : '') +'>' + cities[e.val()][key] + '</option>');
			}
		}
		$("#subCounty").css('display', 'none');
		$("#subCounty #county").attr('disabled', true);
	}
}
function enableCountyCities (e)
{
	var location = $(".acLocationParent").attr('_location');
	$('#acLocation').html('<option value="">Alege localitatea</option>');
	if ('undefined' != typeof (county_cities))
	{
		for ( key in county_cities[e.val()] )
		{
			$('#acLocation').append('<option val="' + county_cities[e.val()][key] + '"'+ (location == county_cities[e.val()][key] ? ' selected' : '') +'>' + county_cities[e.val()][key] + '</option>');
		}
	}
}
function removeMultiselect (id)
{
	$('#'+ id).remove();
}
function redirect(url){
	window.location.href = url;
}
jQuery().ready(function()
{
    if (0 < $("#mgSearch").length)
	{
		$("#mgSearch").bind('submit', function () {
			$('#galerie_media .warningMessage').hide();

			if (3 > $('#tag', $("#mgSearch")).val().length || (!$('#photos', $("#mgSearch")).attr('checked') && !$('#videos', $("#mgSearch")).attr('checked')))
			{
				$('#galerie_media .warningMessage').show();
				return false;
			}
		});
	}
	/*
	if (0 < $(".addNewRecipient a").length)
	{
		$(".addNewRecipient a").click(function(){ 
			if (0 < $("div.defaultRecipi gent").length)
			{
				var _this = $(".addNewRecipient");
				var id = Math.floor(Math.random()*10000000000);
				_this.before('<span id="ss'+ id +'"><a href="javascript: void(0);" onClick="javascript: removeMultiselect(\'ss'+ id +'\')">Sterge destinatar</a></span>');
				var _span = $('span:last', _this.parent());
				_span.prepend($("div.defaultRecipient").clone().removeClass('defaultRecipient'));
				var defRec = $('ss'+ id +' .autocompleteInput');
				defRec.attr(id, 'to'+ id).autocomplete('/index.php?module=Ajax&action=autoComplete&type='+ defRec.attr('_type'),{id:'',value:''});
			}
		});
	}
	*/
	/** Change / uncheck all private messages **/
	if (0 < $("input.checkAll").length)
	{
		$("input.checkAll").click(function(){
			if ($("input.checkAll").attr('checked'))
			{
				$("#messages .messagecheck").attr('checked', true);
			}
			else
			{
				$("#messages .messagecheck").attr('checked', false);
			}
		});
	}
	/**
	 *	Rise "invite fiend" hidden form if error occured
	 */
	if (0 < $("#_friendInvite #warningMessage").length)
	{
		$.popup('friendInvite');
	}
	if (0 < $('#sendMessage').length)
	{

		$('#sendMessage').submit(function() {
			var editor = tinyMCE.activeEditor.getContent();
			if ($('#sendSubject').val().length > 0 && editor.length == 0 )
			{
				return confirm('Esti sigur ca vrei sa trimiti un mesaj fara continut?!');
			}
			return true;
		});
	}
});
