/* On ready */
var is_in_menu = false;
var is_in_site_menu = false;

$(function(){
	
	/* site atual / menu sites */
	$('.site-info').html( $('#site-actions a.selected').html() );
	
	$("#go_search").live('click', function(eve){
		eve.preventDefault();
		window.location = '/search?q=' + encodeURI($("#main_search").val());
		return;
	});
	
	$("#main_search").focus(function(){
		if($(this).val() == $("#main_search_default").val()) $(this).attr('value',''); else return;
	});
	
	$("#main_search").blur(function(){
		if($(this).val() == '') $(this).attr('value',$("#main_search_default").val()); else return;
	});
	
	/* user info */
	
	$(".user-info, #user-actions .email a.e").click(function(eve){
		eve.preventDefault();
		is_in_menu = true;
		$(this).parents('#user-actions').addClass('on');
	});
	
	$("#user-actions").bind('mouseenter', function(){
		is_in_menu = true;
	});
	
	$("#user-actions").bind('mouseleave', function(){
		is_in_menu = false;
		setTimeout(function(){
			if (is_in_menu === false){
				$("#user-actions").removeClass('on');
			}
		}, 1000);
	});
	
	/* site info */
	
	$("#main-menu .add-site, #top-menu .add-site").click(function(eve){
		eve.preventDefault();
		loadSiteWindow();
	});
	
	$("#site-actions li a").click(function(eve){
		eve.preventDefault();
		var value = $(this).attr('href').substr(1);
		if (value == 'new') {
			loadSiteWindow();
		} else {
			window.location = $(this).attr('href');
		}
		$(".menu-my-sites").fadeOut('fast');
	});
	
	$("#site-actions, .site-info, #site-actions .email a").click(function(eve){
		eve.preventDefault();
		is_in_site_menu = true;
		$('#site-actions').addClass('on');
	});
	
	$("#site-actions").bind('mouseenter', function(){
		is_in_site_menu = true;
	});
	
	$("#site-actions").bind('mouseleave', function(){
		is_in_site_menu = false;
		setTimeout(function(){
			if (is_in_site_menu === false){
				$("#site-actions").removeClass('on');
			}
		}, 1000);
	});
	
	$('.act_buy').live('click', function(eve){
		eve.preventDefault();
		//var id = $(this).attr("id").substr(6);
		//buyNow(id);
		window.location = $(this).prev().attr('href');
		
	});
	
	$("a#login").click(function(eve){
		eve.preventDefault();
		openModal($(this).attr("href").substr(1));
		$('#frm_login #user_email').focus();
	});
	
	$("a#signup").click(function(eve){
		eve.preventDefault();
		top.location = "/users/signup";
	});

	// [ modal login - fechar ]
	$('#app-modal-close img').click(function(){
		$('#black-background').css('display','none');
	});
	
	$('.btncancel').live('click', function(){
		$('#black-background').css('display','none');
	});
	
	$('#black-background .abas li a').live('click', function(eve){
		eve.preventDefault();
		var out_content;
		that = $(this);
		
		switch($(this).attr('href').substr(1)){
			case 'login': out_content = '#modal-login'; break;
			case 'sign-up': out_content = '#modal-signup'; break;
			case 'add-user': out_content = '#modal-add-user'; break;
			case 'add-site': out_content = '#modal-add-site'; break;
			default: out_content = '#modal-login';
		}
		$('#app-modal-content').slideUp('fast', function(){
			$('#app-modal-content').html($(out_content).html()).slideDown();
			if( that.attr('href').substr(1) == 'sign-up' ) top.location = '/users/signup';
		});
	});
	
	/* add user */
	$("#app-modal form[name='frm_add_user'] input.submit").live('click', function(eve){
		eve.preventDefault();
		$.post("/users/register_user_site", { user_email: $("#app-modal form#frm_add_user #user_email").val() },
			function(data){
				if (data.status == "1"){
					window.location = '/users/list_all/msg1';
				} else {
					alertThatIn(data.msg, false);
				}
		},"json");
	});
	
	/* add site */
	$("form[name='frm_add_site'] input.submit").live('click', function(eve){
		eve.preventDefault();
		
		$.post("/users/register_site", $(this).parents("form[name='frm_add_site']").serialize(),
			function(data){
				if (data.status == "1") {
					top.location = '/users/edit_plan/2/?ga_newsite';
				} else {
					alertThatIn(data.msg, false);
				}
		},"json");
	});
	
	$(".locale").click(function(eve) {
		eve.preventDefault();
		var locale = $(this).attr("title");
		$.post("/", {locale: locale},
			function(data){
				window.location.reload();
			}
		);		
	});
	
	/* trust developer */
	$(".trusted").live("click", function(){
		trustModal.init();
		trustModal.changeCss(true);
	});
	
	/* trust developer */
	$("#go-to-deployment").live("click", function(){
		window.location.href = '/deployment/form';
	});
	
	$("#app-modal.devel #app-modal-close img").live("click", function(){
		$("#black-background").fadeOut();
		trustModal.changeCss();
	});

});

/* functions */

function alertThat(text, type){
	var text, type;
	
	if(type){
		$('#main-alert').removeClass('error').text(text).slideDown('fast');
	} else {
		$('#main-alert').addClass('error').text(text).slideDown('fast');
	}
	$.scrollTo('#logo-btb', 800);
}

function alertThatIn(text, type){
	var text, type;
	
	if(type){
		$('#app-modal-content .modal-alert').text(text).slideDown('fast');
	} else {
		$('#app-modal-content .modal-alert').addClass('error').text(text).slideDown('fast');
	}
}

function submitSearch(filter, order, category, page){
	
	var filter = (filter == $("#main_search_default").val()) ? "" : filter;
	if (filter != '') {
		$("#divHighlight").css("display","none");
		$("#divResults").css("display","block");
		$("#divResults").html("Search results for: <strong><i>" + filter + "</i></strong>");		
	} else {
		$("#divResults").css("display","none");
		$("#divHighlight").css("display","block");
	}
	var category = (category == 'null') ? "" : category;
	if (typeof page == 'undefined') page = 1;
	$.post("/apps/search_apps", { "filter": filter, "order":order, "category":category, "page": page }, function(data){
		var model = $("#appsResultsModel").html();
		var apps = new Array();
		var num = 0;
		var resultHtml = '';
		if (data.results.length > 0) {
			for (var i in data.results){
				num++;
				var out_name = (data.results[i].name.length < 22) ? data.results[i].name : data.results[i].name.substr(0,21)+'...';
				apps[i] = model.replace("[%APP_NAME%]",out_name);
				
				if(data.results.length < 6)
				{
					apps[i] = apps[i].replace("[%BOX_STYLE%]", " big-box");
					if(num == 1) apps[i] = apps[i].replace("[%BOX_ROUND%]", " top");
					else apps[i] = apps[i].replace("[%BOX_ROUND%]", "");
					var descript = (data.results[i].description.length < 180) ? data.results[i].description : data.results[i].description.substr(0,180)+'...';
				} else {
					apps[i] = (num % 2 == 0) ? apps[i].replace("[%BOX_STYLE%]", " bd2") : apps[i].replace("[%BOX_STYLE%]", " bd1");
					if(num == 1) apps[i] = apps[i].replace("[%BOX_ROUND%]", " type1");
					else if(num == 2) apps[i] = apps[i].replace("[%BOX_ROUND%]", " type2");
					else apps[i] = apps[i].replace("[%BOX_ROUND%]", "");
					var descript = (data.results[i].description.length < 70) ? data.results[i].description : data.results[i].description.substr(0,70)+'...';
				}
				
				var out_price = (data.results[i].user_code_price == 0 || data.results[i].user_code_price == null) ? "FREE" : "$ "+data.results[i].user_code_price;
				
				var out_devel = '<a href="/whois/'+ normalize_friendly_name( data.results[i].developed_by ) +'-'+  data.results[i].user_id +'">';
				out_devel += (data.results[i].developed_by.length < 20) ? data.results[i].developed_by : data.results[i].developed_by.substr(0,20)+'...';
				out_devel += '</a>';
				
				var aType = {0:"Free App", 1: out_price + " (one-time)", 2: out_price + " (per month)"};
				var out_type = aType[data.results[i].user_code_type];
				
				var out_trustIt = (data.results[i].trust == 1) ? '<img src="/img/trust_mini.png" alt="developer with verified account" title="developer with verified account" class="trusted" />' : '';
				
				apps[i] = apps[i].replace("[%APP_DESCRIPTION%]",descript);
				apps[i] = apps[i].replace("[%APP_PRICE%]",out_price);
				apps[i] = apps[i].replace("[%APP_TYPE%]",out_type);
				apps[i] = apps[i].replace("[%APP_VERSION%]",data.results[i].version);
				apps[i] = apps[i].replace("[%RATING%]",data.results[i].stars);
				apps[i] = apps[i].replace("[%APP_DEVELOPED_BY%]",out_devel);
				apps[i] = apps[i].replace("[%APP_TRUST%]",out_trustIt);
				apps[i] = apps[i].replace("[%APP_VERSION_ID%]",data.results[i].user_code_name_friendly + '-' + data.results[i].user_code_id);
				apps[i] = apps[i].replace("[%APP_VERSION_ID%]",data.results[i].user_code_name_friendly + '-' + data.results[i].user_code_id);
				apps[i] = apps[i].replace("[%APP_USER_CODE_ID%]",data.results[i].user_code_id);
				apps[i] = apps[i].replace("[%APP_USER_CODE_ID%]",data.results[i].user_code_id);
				apps[i] = apps[i].replace("[%APP_USER_CODE_ID%]",data.results[i].user_code_id);
				apps[i] = apps[i].replace("[%APP_TITLE%]",data.results[i].name);
				apps[i] = apps[i].replace("[%APP_TITLE%]",data.results[i].name);
				apps[i] = apps[i].replace("[%APP_TITLE%]",data.results[i].name);
				
				if(data.results[i].owner == 0)
				{
					apps[i] = apps[i].replace("[%ACT_BUTTON%]", '<input type="button" id="buyNow'+ data.results[i].version_id +'" name="buy" title="'+ data.results[i].name +'" value="'+ out_price +'" class="act_buy" />');
				}
				else if(data.results[i].owner == 1)
				{
					apps[i] = apps[i].replace("[%ACT_BUTTON%]", '<input type="button" name="buy" value="installed" class="installed" />');
				}
			}
			resultHtml = apps.join("");
		} else {
			resultHtml = 'No apps found.';
		}
		$("#marketPlaceApps").html(resultHtml);
		$("#market_pagination").html(data.links);
		$("#current_page").val(page);

		$("#main-content .app-box .description .rate_stars").each(function() {
			var valor_star = $(this).attr('value');
			var id_star = $(this).attr("id").substr(11);
			$("#rating" + id_star + " li[title='star"+valor_star+"']").prevAll().andSelf().addClass("on");
			
		});
		
	}, "json");
}

function searchPrivateApps() {
	$.post("/apps/search_private_apps", {  }, function(data){
		var model = $("#appsResultsModel").html();
		var apps = new Array();
		var num = 0;
		var resultHtml = '';
		if (data.results.length > 0) {
			for (var i in data.results){
				num++;
				var out_name = (data.results[i].name.length < 22) ? data.results[i].name : data.results[i].name.substr(0,21)+'...';
				apps[i] = model.replace("[%APP_NAME%]",out_name);
				
				if(data.results.length < 6)
				{
					apps[i] = apps[i].replace("[%BOX_STYLE%]", " big-box");
					if(num == 1) apps[i] = apps[i].replace("[%BOX_ROUND%]", " top");
					else apps[i] = apps[i].replace("[%BOX_ROUND%]", "");
					var descript = (data.results[i].description.length < 180) ? data.results[i].description : data.results[i].description.substr(0,180)+'...';
				} else {
					apps[i] = (num % 2 == 0) ? apps[i].replace("[%BOX_STYLE%]", " bd2") : apps[i].replace("[%BOX_STYLE%]", " bd1");
					if(num == 1) apps[i] = apps[i].replace("[%BOX_ROUND%]", " type1");
					else if(num == 2) apps[i] = apps[i].replace("[%BOX_ROUND%]", " type2");
					else apps[i] = apps[i].replace("[%BOX_ROUND%]", "");
					var descript = (data.results[i].description.length < 70) ? data.results[i].description : data.results[i].description.substr(0,70)+'...';
				}
				
				var out_price = (data.results[i].user_code_price == 0 || data.results[i].user_code_price == null) ? "FREE" : "$ "+data.results[i].user_code_price;
				
				var out_devel = '<a href="/whois/'+ normalize_friendly_name( data.results[i].developed_by ) +'-'+  data.results[i].user_id +'">';
				out_devel += (data.results[i].developed_by.length < 20) ? data.results[i].developed_by : data.results[i].developed_by.substr(0,20)+'...';
				out_devel += '</a>';
				
				var aType = {0:"Free App", 1: out_price + " (one-time)", 2: out_price + " (per month)"};
				var out_type = aType[data.results[i].user_code_type];
				
				apps[i] = apps[i].replace("[%APP_DESCRIPTION%]",descript);
				apps[i] = apps[i].replace("[%APP_PRICE%]",out_price);
				apps[i] = apps[i].replace("[%APP_TYPE%]",out_type);
				apps[i] = apps[i].replace("[%APP_VERSION%]",data.results[i].version);
				apps[i] = apps[i].replace("[%RATING%]",data.results[i].stars);
				apps[i] = apps[i].replace("[%APP_DEVELOPED_BY%]",out_devel);
				apps[i] = apps[i].replace("[%APP_VERSION_ID%]",data.results[i].user_code_name_friendly + '-' + data.results[i].user_code_id);
				apps[i] = apps[i].replace("[%APP_VERSION_ID%]",data.results[i].user_code_name_friendly + '-' + data.results[i].user_code_id);
				apps[i] = apps[i].replace("[%APP_USER_CODE_ID%]",data.results[i].user_code_id);
				apps[i] = apps[i].replace("[%APP_USER_CODE_ID%]",data.results[i].user_code_id);
				apps[i] = apps[i].replace("[%APP_USER_CODE_ID%]",data.results[i].user_code_id);
				apps[i] = apps[i].replace("[%APP_TITLE%]",data.results[i].name);
				apps[i] = apps[i].replace("[%APP_TITLE%]",data.results[i].name);
				apps[i] = apps[i].replace("[%APP_TITLE%]",data.results[i].name);
				
				if(data.results[i].owner == 0)
				{
					apps[i] = apps[i].replace("[%ACT_BUTTON%]", '<input type="button" id="buyNow'+ data.results[i].version_id +'" name="buy" title="'+ data.results[i].name +'" value="'+ out_price +'" class="act_buy" />');
				}
				else if(data.results[i].owner == 1)
				{
					apps[i] = apps[i].replace("[%ACT_BUTTON%]", '<input type="button" name="buy" value="installed" class="installed" />');
				}
			}
			resultHtml = apps.join("");
		} else {
			resultHtml = 'No apps found.';
		}
		$("#marketPlaceApps").html(resultHtml);
	}, "json");
}

/* == ALL MODALS == */
function openModal(type, css, html){
	switch(type){
		case 'sign-up':
			$('#app-modal').removeAttr('class').addClass('param');
			$('#app-modal-content').html($("#modal-signup").html());
				break;
		case 'add-user':
			$('#app-modal').removeAttr('class').addClass('param');
			$('#app-modal-content').html($("#modal-add-user").html());
				break;
		case 'add-site':
			$('#app-modal').removeAttr('class').addClass('param');
			$('#app-modal-content').html($("#modal-add-site").html());
				break;
		case 'loading':
			$('#app-modal').removeAttr('class').addClass('loading');
			$('#app-modal-content').html($("#modal-loading").html());
				break;
		case 'custom':
			$('#app-modal').removeAttr('class').addClass(css);
			$('#app-modal-content').html(html);
				break;
		case 'login':
			$('#app-modal').removeAttr('class').addClass('param');
			$('#app-modal-content').html($("#modal-login").html());
				break;
		default:
			$('#app-modal').removeAttr('class').addClass('param');
			$('#app-modal-content').html($("#modal-loading").html());
	}
	$("#black-background").css('display','block');
}

function loadSiteWindow()
{
	openModal("add-site");
}

/* developers trust modal */
var trustModal = {
	init : function(){ openModal('custom', 'devel', this.html) },
	html : function(){
		var out = '<div id="modalTrustDev">'+"\n";
			out += '<h3><span>shield of trust</span>Verified Developer</h3>'+"\n";
			out += '<p>SiteApps Verified Developer have proven themselves to be trustworthy and Realiable.</p>'+"\n";
			out += '<p>We evaluate their applications to ensure that they execute their intended purpose.</p>'+"\n";
			out += '<p>We requere all Verified Developers to offer customer support channels to guarantee your satisfaction.</p>'+"\n";
			out += '<a href="http://support.siteapps.com/entries/20245593-about-verified-accounts" target="_blank" title="learn more...">learn more...</a>'+"\n";
			out += '</div>'+"\n";
		return out;
	},
	changeCss : function(dev){
		if(dev) {
			$('#app-modal-close').css({ 'right':'-25px', 'top':'-25px' }).attr('src','/img/bclose_small.png').find('img').attr('width','35').attr('height','35');
		} else {
			$('#app-modal-close').css({ 'right':'-40px', 'top':'-40px' }).attr('src','/img/bclose.png').find('img').attr('width','43').attr('height','43');;
		}
	}
}

function normalize_friendly_name(full_name){
	var patterns1 = /\s+/g;
	var patterns2 = /[^0-9a-zA-Z_]/g;
	
	var replacements1 = '_';
	var replacements2 = '';
	
	return full_name.replace(patterns1, replacements1).replace(patterns2, replacements2).toLowerCase();
}

/* scroll to */
(function($){var m=$.scrollTo=function(b,h,f){$(window).scrollTo(b,h,f)};m.defaults={axis:'xy',duration:parseFloat($.fn.jquery)>=1.3?0:1};m.window=function(b){return $(window).scrollable()};$.fn.scrollable=function(){return this.map(function(){var b=this,h=!b.nodeName||$.inArray(b.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!h)return b;var f=(b.contentWindow||b).document||b.ownerDocument||b;return $.browser.safari||f.compatMode=='BackCompat'?f.body:f.documentElement})};$.fn.scrollTo=function(l,j,a){if(typeof j=='object'){a=j;j=0}if(typeof a=='function')a={onAfter:a};if(l=='max')l=9e9;a=$.extend({},m.defaults,a);j=j||a.speed||a.duration;a.queue=a.queue&&a.axis.length>1;if(a.queue)j/=2;a.offset=n(a.offset);a.over=n(a.over);return this.scrollable().each(function(){var k=this,o=$(k),d=l,p,g={},q=o.is('html,body');switch(typeof d){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px)?$/.test(d)){d=n(d);break}d=$(d,this);case'object':if(d.is||d.style)p=(d=$(d)).offset()}$.each(a.axis.split(''),function(b,h){var f=h=='x'?'Left':'Top',i=f.toLowerCase(),c='scroll'+f,r=k[c],s=h=='x'?'Width':'Height';if(p){g[c]=p[i]+(q?0:r-o.offset()[i]);if(a.margin){g[c]-=parseInt(d.css('margin'+f))||0;g[c]-=parseInt(d.css('border'+f+'Width'))||0}g[c]+=a.offset[i]||0;if(a.over[i])g[c]+=d[s.toLowerCase()]()*a.over[i]}else g[c]=d[i];if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],u(s));if(!b&&a.queue){if(r!=g[c])t(a.onAfterFirst);delete g[c]}});t(a.onAfter);function t(b){o.animate(g,j,a.easing,b&&function(){b.call(this,l,a)})};function u(b){var h='scroll'+b;if(!q)return k[h];var f='client'+b,i=k.ownerDocument.documentElement,c=k.ownerDocument.body;return Math.max(i[h],c[h])-Math.min(i[f],c[f])}}).end()};function n(b){return typeof b=='object'?b:{top:b,left:b}}})(jQuery);


