/*jslint browser: true, undef: true, laxbreak: true*/
/*global window, jQuery, modeco_context_path */

(function($) {
	var alert = function(msg) {
		window.alert(msg);
	},
	log = function () {
		if ('console' in window && 'log' in window.console) {
			window.console.log(arguments[0]);
		}
	},
	debug = function() {
		if ('console' in window && 'debug' in window.console) {
			window.console.debug(arguments[0]);
		}
	};
	
	$.fn.equalHeight = function() {
		var height = 0, maxHeight = 0;

		// Store the tallest element's height
		this.each(function() {
			var t = $(this),
				border_top = (isNaN(parseInt(t.css('borderTopWidth'),10)) ? 0 : parseInt(t.css('borderTopWidth'),10)),
				border_bottom = (isNaN(parseInt(t.css('borderBottomWidth'),10)) ? 0 : parseInt(t.css('borderBottomWidth'),10));
			
			height = t.height() + parseInt(t.css('paddingTop'), 10) + parseInt(t.css('paddingBottom'), 10) + parseInt(t.css('marginTop'), 10) + parseInt(t.css('marginBottom'), 10) + border_top + border_bottom;
			maxHeight = (height > maxHeight) ? height : maxHeight;
		});

		// Set element's min-height to tallest element's height
		return this.each(function() {
			var t = $(this),
				border_top = (isNaN(parseInt(t.css('borderTopWidth'),10)) ? 0 : parseInt(t.css('borderTopWidth'),10)),
				border_bottom = (isNaN(parseInt(t.css('borderBottomWidth'),10)) ? 0 : parseInt(t.css('borderBottomWidth'),10)),
				mh = maxHeight - (parseInt(t.css('paddingTop'), 10) + parseInt(t.css('paddingBottom'), 10) + parseInt(t.css('marginTop'), 10) + parseInt(t.css('marginBottom'), 10) + border_top + border_bottom);
			
				t.height(mh);
		});
	};
	
	$.deserialize = function(o) {
		if (o && o.indexOf('?') >= 0) {
			o = o.split('?')[1];
		}
			
		var obj = {},
			splitted = o.split('&'),
			s;
		
		for (s in splitted) {
			if (splitted.hasOwnProperty(s)) {
				s = splitted[s].split('=');
				obj[s[0]] = s[1];
			}
		}
		return obj;
	};
	
	$(function() {
		var $ajaxforms = $('.ajaxform');

		//Fix all the corners
		$("#footer li a")
			.wrap('<p class="outer"></p>')
			.corner("round 8px")
			.parent()
			.css('padding', '2px')
			.corner("round cc:#c9d1d5");
		
		//eval fancybox 
		if (typeof($.fn.fancybox) != 'undefined') {
			$('.gallery a').fancybox({
				'zoomSpeedIn': 0,
				'zoomSpeedOut': 0,
				'overlayShow': true 
			});
		}
		
		if (jQuery.fn.pngFix) {
			$('div#guarantee, p.logo').pngFix();
		}
		
		//disabled links must return false
		$(".disabled a[href='#']").click(function() {
			return false;
		});
		
		//The .back links must go back:
		$(".back a").click(function() {
			history.go(-1);
			return false;
		});
		
		$('a[rel^=popup]').click(function() {
			var opt = this.rel.toString().split('?')[1],
				popup = this.popup = window.open(this.href.toString(), 'modecopopup', opt);
			popup.focus();
			return false;
		});

		if ($ajaxforms.length > 0) {
			$.getScript(modeco_context_path + '/resources/scripts/jquery.form-2.43.js', function() {
				var clearProgressListener = function($form) {
					var timer = $form.data('progress_listener_timer');
					if (timer) {
						$form.removeData('progress_listener_timer');
						clearInterval(timer);
					}
				};
				
				log('Forms plugin loaded');
				$ajaxforms.submit(function() {
					var err = 0,
						$form = $(this);
					
					//First of
					$form
						.find('.image')
							.each(function() {
								var val = $(this).val(),
									ext = val.toLowerCase().substring(val.lastIndexOf('.') + 1);
								
								if (ext != 'jpg' && ext != 'png' && ext != 'gif') {
									alert('Το αρχείο πρέπει να είναι φωτογραφία τύπου jpg, png ή gif');
									err++;
									return false;
								}
							});

					if (err > 0) {
						return false;
					}
					
					//In any other case continue sending the form
					$form.ajaxSubmit({
							beforeSubmit: function(data, $form, opt) {
								if ($form.is('.withprogresslistener')) {
									log('Must fire a progresslistener');
									
									$form.hide();
									
									var $msg = $('<strong>Αποστολή...</strong>').insertAfter($form),
										timer = setInterval(function() {
											$.getJSON(modeco_context_path + '/status/', function(json) {
												debug(json);
												if ('fileupload_bytes_read' in json && 'fileupload_content_length' in json) {
													$msg.html('Εστάλησαν: <strong>' + json.fileupload_bytes_read +'</strong> / ' + json.fileupload_content_length);
												}
											});
										}, 3000);
									
									$form.data('progress_listener_timer', timer);
								}
							},
							success: function(resp, status, xhr, $form) {
								var json = $.evalJSON(resp);
								clearProgressListener($form);
								
								if (json && 'exception' in json) {
									log(json.exception + ': ' + json.message);
									alert(json.exception == 'FileSizeLimitExceededException' ? 'Το αρχείο είναι πολύ μεγάλο, βεβαιωθείτε ότι είναι κάτω των 5mb' : 'Υπήρξε κάποιο πρόβλημα κατά την αποστολή του email. Παρακαλώ ξαναπροσπαθείστε αργότερα');
									return;
								}
								//In any other case we assume that we successfully send the email:
								$form.parent().replaceWith('<strong>Ευχαριστούμε για την επικοινωνία, σύντομα θα έχετε νέα μας</strong>');
							}
					});
					
					return false;
				});
			});
		}
	});
	
	//Set the equality of the columns
	$(window).load(function() {
		//Set the equality of the columns
		$('#menu-column, #content, #right-column').equalHeight();

		var $plist = $('ul.products-list'),
			$li,
			i;
		
		if ($plist.length > 0) {
			$li = $('li', $plist);
			i = 0;
			while (true) {
				$li.slice(i*3, (++i)*3).equalHeight();
				if (i*3 >= $li.length) {
					break;
				}
			}
		}
	});

})(jQuery);
