/*\------------------------------------------------------------------------

	>> www.sync.gr
	>> 09/02/08				
	>> Kostis Sakkas [sync team]			
		
------------------------------------------------------------------------\*/


jQuery.sync = {
	
/*\------------------------------------------------------------------------
	module methods
------------------------------------------------------------------------\*/

	apps	:	{
		
		hide	:	function(id, pos, title){
			try{
				if ("" == id) throw new Error("APP ID CANNOT BE EMPTY");
				$.post("/apps/hide/",
					{id: id, pos: $("#app_"+id).parent().attr('id')},
					function(json) {
						var o = $.parseJSON(json);
							if(o.error)	alert(o.error);
							else{ 
								equal();
								var r = "<div id='app_"+id+"' class='mod'><div class='alert'>Μπορείς ανά πάσα στιγμή να επαναφέρεις το <strong>"+title+"</strong> στην σελίδα σου μέσω των <a href='/account/apps/'>ρυθμίσεων σου</a></div></div>";
								$("#app_"+id).fadeOut('slow', function(){
    								$(r)
									.insertAfter( $(this) )
									.fadeIn('slow')
									.animate({opacity: 1.0}, 3000)
									.fadeOut('slow', function() {
										$(this).remove();
									});
								 });
							}
						 }
					);

			}
			catch(err){ alert("An error occured!\n Error detail : " + err.message);}
		},
		
		/*\----------------------------------------------------------------
			resort
		----------------------------------------------------------------\*/
		
		resort	:	function(el){
			
			var id = $(el).attr("id").split("_")[1];
			var pos = $(el).parent().attr('id');
			
			var	length	= $(el).parent().children().size() - 1;
			var cnt		= 1;
			var list 	= '';
	
			$(el).parent().children().each(function (i) {
				var appId = $(this).attr("id");
				if(undefined != appId){
					var mod = $(this).attr("id").split("_")[1];
					if(undefined != mod)
						list += (cnt==length) ? mod : mod + ',';
				}
				cnt++;
			  });	
			$.post("/apps/resort/",
				{id:id, list: list, pos:pos},
				function(json) {
					var o = $.parseJSON(json);
						if(o.error)
							alert(o.error)
					 }
				);
			equal();
		},
		
		/*\----------------------------------------------------------------
			toggleSortable
		----------------------------------------------------------------\*/
		
		toggleSortable	:	function(el, cont){
			var val = $(el).attr("title");
			if (val == 'Enable'){
				$(el).html('Κλείσιμο διαμόρφωσης');
				$(el).attr("title", 'Disable');
				$(cont).sortableEnable();
				$('.mod_header').css("cursor", "move");
				$('.mod_header h3').attr("title", "drag and drop");
				$('.mod').addClass("ghost");
				$('#toggle-pos-txt').removeClass('hidden');
			}
			else{
				$(el).html('Διαμόρφωση σελίδας');
				$(el).attr("title", 'Enable');
				$(cont).sortableDisable();
				$('.mod_header').css("cursor", "help");
				$('.mod_header h3').attr("title", "press enable to drag");
				$('.mod').removeClass("ghost");
				$('#toggle-pos-txt').addClass('hidden');
			}
		},
		
		/*\----------------------------------------------------------------
			modal
		----------------------------------------------------------------\*/
		
		modal	:	function(app){
			
			var d = new Date();
			seed = d.getTime();
			
			$.get("/apps/"+app+"/modal/?"+seed, function(data){
				// create a modal dialog with the data
				$(data).modal({
					close: false,
					overlayId: 'modalOverlay',
					containerId: 'modalContainer',
					iframeId: 'modalIframe',
					onOpen: jQuery.sync.modal.open,
					onShow: jQuery.sync.modal.show,
					onClose: jQuery.sync.modal.close
				});
			});			
			
		},
		
		/*\----------------------------------------------------------------
			ajax
		----------------------------------------------------------------\*/
		
		ajax	:	function(app, what, id){
			var d = new Date();
			seed = d.getTime();
			$.get("/apps/ajax/?"+seed, 
				  {app:app, what:what, id:id},
				function(data){$("#load-"+app).replaceWith(data);}
			);			
		}
	},

	
/*\------------------------------------------------------------------------
	modal methods
------------------------------------------------------------------------\*/

	modal	:	 {	
		message: null,
		
		open: function (dialog) {
			dialog.overlay.fadeIn(200, function () {
				dialog.container.fadeIn(200, function () {
					dialog.content.fadeIn(200, function () {
						$('#modalContainer #name').focus();
					});
					// resize the textarea for safari
					if ($.browser.safari) {
						$('#modalContainer textarea').attr({
							cols: '37',
							rows: '8'
						});
					}
				});
			});
		},
	
		show: function (dialog) {
			$('#modalContainer .send').click(function (e) {
				e.preventDefault();
				
				$('#modalContainer .loading').html('<p>Σύνδεση με server...</p>');
				$('#modalContainer .loading').animate({
					height: '25px'
					}, function () {
						$('#modalContainer .loading').fadeIn(200, function () {
							$.ajax({
								url: '/apps/update/',
								data: $('#modalContainer form').serialize() + '&action=send',
								dataType: 'html',
								complete: function (xhr) {
									$('#modalContainer .loading').fadeOut(200, function () {
										var o = $.parseJSON(xhr.responseText);
										if(o.error == '')
											$('#modalContainer .loading').html("<p>"+o.reply+"</p>").fadeIn(200);
										else
											$('#modalContainer .loading').html("<p>Error Msg: "+o.error+"</p>").fadeIn(200);
									});
								},
								error: jQuery.sync.modal.error
							});
						});
					});
				
			});
		},
		
		close: function (dialog) {
			refreshParent();
			dialog.content.fadeOut(200, function () {
				dialog.container.fadeOut(200, function () {
					dialog.overlay.fadeOut(200, function () {
						$.modal.remove(dialog);
						
					});
				});
			});
		},
		
		error: function (xhr) {
			alert(xhr.statusText);
		},
	
		showError: function () {
			$('#modalContainer .message').html($('<div class="error"></div>').append(jQuery.sync.modal.message)).fadeIn(200);
		}
	},

	
/*\------------------------------------------------------------------------
	image methods
------------------------------------------------------------------------\*/

	image	:	{
		
		/*\----------------------------------------------------------------
			add image to DOM
		----------------------------------------------------------------\*/
		
		add	:	function(image, path){
			var fullImagePath = path + image;
			var parDoc = window.parent.document;
			parDoc.getElementById('avatar-img').src= fullImagePath;
			parDoc.getElementById('upload_status').innerHTML= "Η εικόνα αποθηκεύτηκε με επιτυχία.";
			parDoc.getElementById('upload_status').className= "tab-success";
			parDoc.getElementById('avatar_image').value = '';
			
			parDoc.getElementById('rem-avatar').innerHTML= "<a href='javascript:void%200;' onclick='jQuery.sync.image.remove()'>Διαγραφή εικόνας</a>";
			parDoc.getElementById('rem-avatar').className= "rem-avatar";
			
			$.post("/account/image/add/",{img: encodeURIComponent(image)},function(json) {});

		},
		
		/*\----------------------------------------------------------------
			remove the image and unlink it from the local dir
		----------------------------------------------------------------\*/
		
		remove	:	function(){
			$('#avatar-img').attr("src","http://"+STATIC_ROOT+"/_img/avatar64.jpg");
			$('#rem-avatar').html("").removeClass("rem-avatar");
			$('#upload_status').removeClass().addClass("tab-success").html("Η εικόνα διαγράφηκε με επιτυχία.");
			$.post("/account/image/remove/",{fu:'bar'},	function(json){});
			
		}
	},
	
	feed	:	{
	
		replyDIV	:	null,
	
		claim	:	function(id, reply){
			$.get("/blog/" + id  + "/claim/index.html",
				{id:id},
				function(json) {
					var o = $.parseJSON(json);
						if(o.err != "")
							$("#"+reply).addClass("claim-fail").html(o.err);
						else
							$("#"+reply).addClass("claim-success").html(o.reply);
					 }
				);
		},
	
		preloader	:	function(div, style){
			try{
				var el = $(div);
				if (!el) throw new Error("el is not found"); 
				el.className = style;
				el.innerHTML = 'Ανάγνωση του RSS';
			}
			catch(errv){
				alert("Η εφαρμογή δε μπορεί να συνδεθεί με το server!\n"+
					  "Error detail : " + errv.message);
			}
		},
	
		pingAddBlog	:	function(o){
			var el = $(obj.feed.replyDIV);
			if(o.err != ""){
				el.className = 'error';
				el.innerHTML = o.err;
			}
			else{
				el.className = 'success';
				el.innerHTML = o.reply;
			}
		}
	},
	
	blog	:	{
		
		add	:	function(id){
			try{
				if ("" == id) throw new Error("id CANNOT BE EMPTY"); else obj.user.id = id;
				var url = "/blog/" + id  + "/add/index.html";
				var pid = arguments[1];
				obj.user.page =  (pid == undefined)	? "" : 	pid;
				obj.AJAX.httpRequest("GET", url, true, obj.user.handleRequest);
			}
			catch(err){
				alert("An error occured!\n"+
					  "Error detail : " + err.message);
			}
		},
	
		remove	:	function(id){
			try{
				if ("" == id) throw new Error("id CANNOT BE EMPTY");
				$.get("/blog/" + id  + "/remove/index.html",
					{id:id},
					function(json) {
						$('#blog_'+id).fadeOut(500);
					});
			}
			catch(err){
				alert("An error occured!\n"+
					  "Error detail : " + err.message);
			}
		}
	}
	
}


$(document).ready(function () {
							

/*\------------------------------------------------------------------------
	initialize sortable for profile modules
------------------------------------------------------------------------\*/
	
	$("#content.sort").sortable({items: ".mod", helper:function(){return "h3.handle"}, containment:'document', hoverClass: "ghost", stop:function(){return jQuery.sync.apps.resort(this)}});
	$('#content.sort').sortableDisable();
	
/*\------------------------------------------------------------------------
	upload a file through a hidden iframe
------------------------------------------------------------------------\*/

	jsUpload = function(upload_field){
		var re_text = /\.jpg|\.jpeg|\.png|\.gif/i;
		var filename = upload_field.value;
		/* Checking file type */
		if (filename.search(re_text) == -1)	{
			$('#upload_status').removeClass().addClass('tab-fail').html("το αρχείο που δοκιμάζεις να ανεβάσεις δεν έχει κατάληξη εικόνας (jpg, gif, png)");
			upload_field.form.reset();
			return false;
		}
		upload_field.form.submit();
		$('#upload_status').removeClass().addClass('tab-load');
		$('#upload_status').html("Σύνδεση με το server. Αποστολή αρχείου");
		return true;
	}
	
/*\------------------------------------------------------------------------
	
	Replaces email addresses with the title attr.
	credits : initial idea from http://www.badboy.ro/articles/2005-01-25/index.php
	
------------------------------------------------------------------------\*/

	emailCloak = function() {
		if (document.getElementById) {
			var alltags = document.all? document.all : document.getElementsByTagName("*");
			for (i=0; i < alltags.length; i++) {
				if (alltags[i].className == "emailCloak") {
					var oldText = alltags[i].firstChild;
					var emailAddress = alltags[i].firstChild.nodeValue;
					var user = emailAddress.substring(0, emailAddress.indexOf("("));
					var website = emailAddress.substring(emailAddress.indexOf(")")+1, emailAddress.length);
					var newText = user+"@"+website;
					var a = document.createElement("a");
					a.href = "mailto:"+newText;
					var address = document.createTextNode(newText);
					a.appendChild(address);
					alltags[i].replaceChild(a,oldText);
				}
			}
		}
	}
	
/*\------------------------------------------------------------------------
	
	Opens new windows via rel="external"
	url : http://www.brucelawson.co.uk/index.php/2005/opening-links-in-new-windows-in-xhtml-strict/
	
------------------------------------------------------------------------\*/

	externalLinks = function() {
		if (!document.getElementsByTagName) return;
		var anchors = document.getElementsByTagName("a");
		for (var i=0; i<anchors .length; i++) {
			var anchor = anchors[i];
			if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") {
				anchor.target = "_blank";
				anchor.title = (anchor.title != "") ? anchor.title+" (Ανοίγει σε νέο παράθυρο)" : "Ανοίγει σε νέο παράθυρο";
				anchor.className = (anchor.className != '') ? anchor.className+' external' : 'external';
			}
		}
	}


/*\------------------------------------------------------------------------
	
	Position footer div at the bottom of the page using DOM
	
	Source from the precious AListApart.com
	Article : Exploring Footers
	URL : http://www.alistapart.com/articles/footers/
	[changed the setFooter() a bit]

------------------------------------------------------------------------\*/

	getWindowHeight = function() {
		var windowHeight = 0;
		if (typeof(window.innerHeight) == 'number') {
			windowHeight = window.innerHeight;
		}
		else {
			if (document.documentElement && document.documentElement.clientHeight) {
				windowHeight = document.documentElement.clientHeight;
			}
			else {
				if (document.body && document.body.clientHeight) {
					windowHeight = document.body.clientHeight;
				}
			}
		}
		return windowHeight;
	}
		
	setFooter = function() {
		if (document.getElementById) {
			var windowHeight = getWindowHeight();
			if (windowHeight > 0) {
				
				var headerElement  = document.getElementById('hwrpr');
				var headerHeight  = headerElement.offsetHeight;
				
				var contentElement = document.getElementById('content');
				if (!contentElement) contentElement = document.getElementById('account');
				if (!contentElement) contentElement = document.getElementById('wmain');
				var contentHeight  = contentElement.offsetHeight;
				
				var footerElement = document.getElementById('footer-wrapper');
				var footerHeight  = footerElement.offsetHeight;
				
				if (headerHeight + contentHeight + footerHeight < windowHeight) {				
					contentElement.style.height= windowHeight - (headerHeight + footerHeight + 31)  + 'px';
					//alert("CONTENT : " + contentElement.style.height);
	
				}
				//alert("WINDOWHEIGHT : " + windowHeight + "\r\nHEADER : " + headerHeight + "\r\nCONTENT : " + contentHeight+ "\r\n FOOTER : " + footerHeight);
			}
		}
	}
	
	equal	=	function(){
		/*
		var mHeight  		= $('#m').height();
		var rHeight  		= $('#r').height();
		//alert("MAIN : " + mHeight + " \r\nRIGHT : " + rHeight);
		if (mHeight <= rHeight) {				
			$('#m').css('height', rHeight - mHeight);
		}
		else
			$('#r').css('height', mHeight - rHeight);
		*/
		return null;
	}
	
	
/*\------------------------------------------------------------------------
	highlight	
------------------------------------------------------------------------\*/

	highlight	=	function(el, cont){
		$(cont + ">dl").removeClass("highlight");
		$(el).parent().parent().removeClass("flash").addClass("highlight");
	}
	
/*\------------------------------------------------------------------------
	toggleHighlight	
------------------------------------------------------------------------\*/

	toggleHighlight	=	function(el){
		if($(el).attr('checked'))
			$(el).parent().parent().removeClass("flash").addClass("highlight");
		else
			$(el).parent().parent().removeClass("flash highlight");
	}
	
/*\------------------------------------------------------------------------
	toggle app visibility on users profile
------------------------------------------------------------------------\*/

	toggleApp	=	function(el, id, pos){
		var checked = ($(el).attr('checked')) ? 1 : 0;
		$.post("/apps/toggle/",
			{id: id, checked: checked, pos:pos},
			function(json) {
				var o = $.parseJSON(json);
				if(o.error)	$("#apps-err").html(o.error);
			 }
		);
		(checked) ?	$(el).parent().parent().removeClass("flash").addClass("highlight") : $(el).parent().parent().removeClass("flash highlight");
	}
	
	
/*\------------------------------------------------------------------------
	flash	
------------------------------------------------------------------------\*/

	flash	=	function(el){$(el).addClass("flash");}
	
/*\------------------------------------------------------------------------
	unflash	
------------------------------------------------------------------------\*/

	unflash	=	function(el){$(el).removeClass("flash");}
	
	
/*\------------------------------------------------------------------------
	showlogin	
------------------------------------------------------------------------\*/

	showlogin	=	function(){
		if ($("#login").attr("class") == "hidden")
			$("#login").removeClass("hidden").addClass("visible");
		else
			$("#login").removeClass("visible").addClass("hidden");
	}
	
/*\------------------------------------------------------------------------
	showlogin	
------------------------------------------------------------------------\*/

	refreshParent	=	function () { 
		window.parent.location.reload(); 
	} 
	
/*\------------------------------------------------------------------------
	checkusername (unique, not used)	
------------------------------------------------------------------------\*/

	checkusername	=	function(){
		val = $("#text_username").val();
		if('' != val){
			$.post("/checkusername.html",
				{val: val},
				function(json) {
					var o = $.parseJSON(json);
					$("#warn_username").html(o.reply);
				}
			);
		}
	}
	
/*\------------------------------------------------------------------------
	checkemail (unique, not used)	
------------------------------------------------------------------------\*/

	checkemail	=	function(){
		val = $("#text_email").val();
		if('' != val){
			$.post("/checkemail.html",
				{val: val},
				function(json) {
					var o = $.parseJSON(json);
					$("#warn_email").html(o.reply);
				}
			);
		}
	}
	
	
	termsofuse = function(){
		newwindow=window.open('/terms.php', 'terms', 'resizable=1,toolbar=0,location=0,status=0,menubar=0,scrollbars=yes,width=700,height=450');
		newwindow.focus();
	};
	
	privacypolicy = function(){
		newwindow=window.open('/privacy.php', 'privacy', 'resizable=1,toolbar=0,location=0,status=0,menubar=0,scrollbars=yes,width=700,height=450');
		newwindow.focus();
	};
	
/*\------------------------------------------------------------------------
	window onload and onresize events
------------------------------------------------------------------------\*/
	
	$(window).load(function(){	externalLinks();/*setFooter();*/equal();});
	$(window).resize(function(){/*setFooter();*/equal();});
	
});

