/********************************************************
	Netkata WEB SOLUTIONS
	visit www.netkata.com or email info@netkata.com
*********************************************************/

// namespace
if (!namespace) {
	var namespace = {};
		namespace.ui = {};		// user interface 
		namespace.ev = {};		// event publish / subscribe system
		namespace.xhr = {};
}

// event delegation
jQuery.fn.delegate = function(eventType, rules) {
  return this.bind(eventType, function(e) {
    var target = $(e.target);
    for(var selector in rules)
      if(target.is(selector)) 
        return rules[selector].apply(this, arguments)
  })
}


namespace.ui = new function() {
	var that = this;
	this.loaderImg = null;
	this.companyMail = 'info';
	this.companyMailDomain = 'netkata.com';
	
	// set element heights and widths
	this.layout = new function() {	
		this.recalculate = function() {
			var h = $(window).height();
			// .. 
		}
	};
	
	this.highlighGallery = function(target){
		var linkNode = $(target.target).parent();
		var linkUrl = linkNode.attr("href");
		var preview = linkNode.parent().prev();
		var previewImg = preview.find(".previewHolder").find("img");
		var title = linkNode.attr("title"); 
		var selected = linkNode.parent().find("[class*=selected]");
		selected.removeClass("selected");
		linkNode.addClass("selected");
		preview.find("p").html(title);
		previewImg.fadeTo(300,0.01,function(){
			previewImg.load(function(){
				previewImg.fadeTo(300,1);
			});	
			previewImg.attr("src",linkUrl);
		}); 
	}
	
	this.showLoader = function(){
		$("#contactForm").hide();
		that.loaderImg = document.createElement("img");
		that.loaderImg.setAttribute("src","/images/loader.gif");
		that.loaderImg = $(that.loaderImg);
		$(".formIntro").after(that.loaderImg);
	}
	
	this.hideLoader = function(){
		if(that.loaderImg !== null){
			that.loaderImg.hide();
		}
	}
	
	this.displayCallback = function(msg, className){
		var div = document.createElement("div");
		div.className = className;
		div.innerHTML = msg;
		$('#contactForm').before($(div));
	}
	
	this.addMailAddress = function(){
		$(".netkataEmail").each(function(){
			$(this).html('<a href="mailto:'+that.companyMail+'@'+that.companyMailDomain+'">'+that.companyMail+'@'+that.companyMailDomain+'</a>');		
		}) ;
	}
	
	
};


/********************************************************************** EVENTS */
// 	Global events pub/sub manager:
namespace.ev = new function() {
	var that = this;
	this.isValidated = false;
	
	// app start
	$(document).bind("init.data", function(e, jsonData) {
		// eg. namespace.init(jsonData);
	});
			// to trigger an evet:
			// $(document).trigger("init.data", [someObject, Or, Variable]);
		
	// UI events bound to DOM nodes
	this.bindDomEvents = function() {
		$(".thumbs").delegate("click", {
			"img" : function(e){ namespace.ui.highlighGallery(e); return false; },
			"a" : function(e){ namespace.ui.highlighGallery(e); return false; }
		});
		
		$('#contactForm').delegate("click",{
			"input": function(){
				namespace.ev.validateContactForm();
			} 
		})
	};
		
	this.validateContactForm = function(){
		
		if(!that.isValidated){
			var validator = $("#contactForm").validate({
				onkeyup: true,
				rules: {
					"contact[name]": "required",
					"contact[phone]": {
						required:function(){
							if($("#email").val() == ""){
								return true;						
							}else{
								return false;
							}
						}
					},
					"contact[email]": {
						required: function(){
							if ($("#phone").val() == "") {
								return true;
							}else{
								return false;
							}			
						},
						email: true
					},
					"contact[msg]": "required"		
				},
				messages: {
					"contact[name]": dict.validate_name,
					"contact[phone]": dict.validate_phone,
					"contact[email]": {
						required: dict.validate_email,
						minlength: dict.validate_email,
						email: dict.validate_email
					},
					"contact[msg]": dict.validate_msg
				},
				// the errorPlacement has to take the table layout into account
				errorPlacement: function(error, element) {
					error.prependTo( element.parent());
				},
				// specifying a submitHandler prevents the default submit, good for the demo
				submitHandler: function() {
					namespace.xhr.sendContactForm();
				},
				// set this class to error-labels to indicate valid fields
				success: function(label) {
					label.remove();
				}
			});
			that.isValidated = true;
		}
	}
	
			
	// window resize (crazy timeouts for IE6)
	var resizeTimer = null;	
	$(window).resize( function() {
		if (resizeTimer) { clearTimeout(resizeTimer); };
//		resizeTimer = setTimeout(function() { namespace.ui.recalculate(); }, 100);
	});
};

namespace.xhr = new function() {
	this.sendContactForm = function(){
		$.post(
			"/xhr/send_mail.php",
			{
				"contact[name]": $("#name").val(),
				"contact[email]": $("#email").val(),
				"contact[phone]": $("#phone").val(),
				"contact[msg]": $("#msg").val() 
			},
			function(response){
				var resp = JSON.parse(response);
				namespace.ui.hideLoader();
				if(resp.sent){
					namespace.ui.displayCallback(resp.callback, 'success');
				}else{
					namespace.ui.displayCallback(resp.callback, 'error');
					namespace.ui.showForm();
				}
			}
		);
		namespace.ui.showLoader();
	}
}


/********************************************************************** APP INIT */
$(document).ready(initApp);

function initApp() {
	namespace.ev.bindDomEvents();
	namespace.ui.addMailAddress();
	
}