﻿function menudesp() {
	if(document.inprogress == 0) {
		$("#menuprodback").css("display", "block");
		document.inprogress = 1;
		if($("#menuprodback").height() != 0) {
			document.a = $("#menuprodback").height();
			$("#menuprodback").animate({
				height : "12px"
			}, 450, function() {
				$("#pie").animate({
					height : "0px"
				}, 26);
				$("#menuprodback").animate({
					height : "0",
					marginBottom : "0"
				}, 26, function() {
					document.inprogress = 0;
				});
			});
		} else {
			$("#pie").animate({
				height : "12px"
			}, 26, function() {
				$("#pie").animate({
					height : "23px"
				}, 26)
				$("#menuprodback").animate({
					height : "23px",
					marginBottom : "50px"
				}, 26, function() {
					$("#menuprodback").animate({
						height : document.a + "px"
					}, 450, function() {
						document.inprogress = 0;
					});
				});
			});
		}
	}
}


$(document).ajaxSend(function(event, xhr, settings) {
	function getCookie(name) {
		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;
	}

	function sameOrigin(url) {
		// url could be relative or scheme relative or absolute
		var host = document.location.host;
		// host + port
		var protocol = document.location.protocol;
		var sr_origin = '//' + host;
		var origin = protocol + sr_origin;
		// Allow absolute or scheme relative URLs to same origin
		return (url == origin || url.slice(0, origin.length + 1) == origin + '/') || (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
		// or any other URL that isn't scheme relative or absolute i.e relative.
		!(/^(\/\/|http:|https:).*/.test(url));
	}

	function safeMethod(method) {
		return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
	}

	if(!safeMethod(settings.type) && sameOrigin(settings.url)) {
		xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
	}
});
function fadeAtLoad(el) {
	dly = 0;
	$(el).each(function() {
		$(this).delay(dly).fadeIn('slow');
		dly += 100;
	});
}

function activeSch() {
	repairBlack();
	centerLoad();
	$("#contactBlack").fadeTo(500, 0.6);
	$("#fichatecnica").fadeIn();
	_gaq.push(['_trackEvent', 'Ficha técnica', 'Abrir', 'Cierre de la ficha técnica apartado productos']);
}

function closeSch() {
	$("#fichatecnica").fadeOut(50);
	$("#contactBlack").fadeOut(50);
	_gaq.push(['_trackEvent', 'Ficha técnica', 'Cerrar', 'Cierre de la ficha técnica apartado productos']);
}

function switchse(kind) {
	if(kind == 'n') {
		$("#product_submit").attr('value', "noticias");
		$("#id_tipo").attr('value', "n");
		$(".scrollsearch").hide();
	} else {
		$("#product_submit").attr('value', "productos");
		$("#id_tipo").attr('value', "p");
		$(".scrollsearch").hide();
	}
}

function loadCont(realUrl, anUrl) {
	reqContact(realUrl);
	if(anUrl != ""){
		_gaq.push(['_trackPageview', anUrl]);
	}
}

function countGAsend(anUrl) {;
	if(anUrl != ""){
		_gaq.push(['_trackPageview', anUrl]);
	}
}

function enviaropinion(){
	allok = 1;
	if($("input[name='encontro']:checked").val()==undefined){
		$(".encontrolabelp").html("¿Encontró con facilidad lo que buscaba? <ul class='errorlist'><li>Este campo es obligatorio</li></ul>");
		allok = 0;
	} else {
		$(".encontrolabelp").html("¿Encontró con facilidad lo que buscaba?");
	}
	if($("textarea[name='comentario']").val() == "") {
		$(".comentariolabelp").html("Comentario <ul class='errorlist'><li>Este campo es obligatorio</li></ul>");
		allok = 0;
	} else {
		$(".comentariolabelp").html("Comentario");
	}
	if(allok == 1) {
		var hoy    = new Date();
		var toLive = new Date();
		var offset = hoy.getTime() + (60 * 24 * 60 * 60 * 1000);

		toLive.setTime(offset);
		var tDia  = toLive.getDate();
		var tMes  = toLive.getMonth();
		var tAnio = toLive.getFullYear();

		var lasOpciones = { expiresAt: new Date( tAnio, tMes, tDia ) };

		$.cookies.set( 'opinion', '1', lasOpciones );

		$(".enviaropi").attr("value", "Enviando...").attr("onclick", "void(0)");

		setTimeout(function(){ $("#opinion").fadeOut("slow"); }, 2000);

		$.post("/xhr_test", {
				encontro: $("input[name='encontro']:checked").val(),
				comentario: $("textarea[name='comentario']").val()
			},
			function(data) {
				if(data == "ok")
					$("#opinion").html("<h1>¡Gracias por ayudarnos a mejorar!");
			}
		);
	}
}

function main() {
	if( $.cookies.test() )
		if ( $.cookies.get( 'opinion' ) === null )
			$("#opinion").fadeTo("normal", 0.8);

	$("#cerrarOpinion").click(function() {
		$('#opinion').fadeOut('normal');
		$.cookies.set( 'opinion', '1');
	});

	$('img').each(function() {
		a = $(this).attr("src");
		a = a.split(".");
		ext = a[a.length - 1];
		if(ext == "png" || ext == "PNG") {
			$(this).css('behavior', 'url(/static/iepngfix/iepngfix.htc)');
		}
	});
	// Search engine menu scroll version debug //
	$(".searchwrapper img").click(function() {
		if($(".scrollsearch:hidden").length == 0) {
			$(".scrollsearch").hide();
		} else {
			$(".scrollsearch").animate({
				height : ['show', 'easeOutCirc'],
				opacity : 'show'
			}, 500);
		}
	});
	// Cache todas partes
	$(["/static/img/searchFocusInput.jpg"]).preload();
	$(["/static/img/icons/Home-hover.png"]).preload();

	fadeAtLoad(".normal, .wide, .content, .contentshort, .contentlong");

	$('.redes').fadeIn('slow');

	$(".info").parent().hover(function() {
		$(".info", this).fadeTo("fast", "0.9");
	}, function() {
		$(".info", this).fadeOut("fast");
	});
	$(".noticiainfo").parent().hover(function() {
		$(".noticiainfo", this).fadeTo("fast", "0.9");
	}, function() {
		$(".noticiainfo", this).fadeOut("fast");
	});
	sly = 0

	$('.redes img, .net img').each(function() {
		$(this).delay(sly).fadeTo('slow', 0.5);
		sly += 200;
		$(this).hover(function() {
			$(this).fadeTo('fast', 1);
		}, function() {
			$(this).fadeTo('fast', 0.5);
		});
	});
	$(".normal, .wide").hover(function() {
		$(".redtab", this).animate({
			marginTop : "-60"
		}, 400);
	}, function() {
		$(".redtab", this).animate({
			marginTop : "0"
		}, 200);
	});
	$("#financiafade").hover( function(){ $(this).fadeTo(100, 0.7) }, function(){ $(this).fadeTo(100, 1) } )
	$("#hmt").hover(function() {$("#home").attr("src", "/static/img/icons/Home-hover.png");
	}, function() {$("#home").attr("src", "/static/img/icons/Home.png");
	});
	$("#id_clave").focus(function() {
		$(this).css("background-image", "url(/static/img/searchFocusInput.jpg)");
		$(this).css("color", "black");
	});
	$("#id_clave").focusout(function() {
		$(this).css("background-image", "url(/static/img/searchBackInput.jpg)");
		$(this).css("color", "#FEFEF1");
	});
	document.a = $("#menuprodback").height();
	$("#menuprodback").css("height", "0");
	document.inprogress = 0;
	document.going = 0;
	$(".searchwrapper").hover(function() {
		$(".downb").animate({
			height : ['show', 'easeOutCirc'],
			opacity : 'show'
		}, 500);
	}, function() {
		$(".downb").hide();
	})
	$(".b").each(function() { $(this).hover(function() {
			$("p", this).css("background-color", "#3A474F");
			$(".scrolldown", this).animate({
				height : ['show', 'easeOutCirc'],
				opacity : 'show'
			}, 500);
		}, function() {
			$("p", this).css("background-color", "transparent");
			$(".scrolldown", this).hide();
		});
	});
	if(document.page == "trabajos-recientes") {
	}

	if(document.page == "inicio") {
		function replaceURLWithHTMLLinks(text) {
			var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
			return text.replace(exp,"<a target='_blank' title='Ver Link' href='$1'>$1</a>"); 
		}

		var acc = "soticArg";
		$.getJSON("http://twitter.com/statuses/user_timeline/" + acc + ".json?count=1&callback=?", function(json) {
			var lastTweet = replaceURLWithHTMLLinks(json[0].text);
			var tweetTime = json[0].created_at;
			var tweetTime = relative_time(json[0].created_at);
			$("#twitter_update_list").html("<p>" + lastTweet + " - " + tweetTime + "</p>");
		});
	}

	$(".contactus, .contactusmain, .contactusred").click(function() {
		loadCont('/contacto/consulta', '/consulta-asesoramiento');
	});
	$(".worksotic").click(function() {
		loadCont('/contacto/trabaja', '/trabaja-en-sotic');
	});
	$(".helpus").click(function() {
		loadCont('/contacto/conformidad', '/ayudenos-a-mejorar');
	});
	$(".mapcontact").click(function() {
		loadCont('/contacto/donde', '/contacto');
	});
	$(".boletin").click(function() {
		loadCont('/contacto/boletin', '/inscripcion-a-boletines');
	});
	$('body').keyup(function(e) {
		if(e.keyCode == 27) {
			closeForm(0);
		}
	});
	activateProductos(0);
	$(".upanddown").fadeIn();
	if(document.page == "productos" || document.page == "empresa" | document.page == "trabajos-recientes") {
		$(".mn li").each(function() {

			this.original = $("img", this).attr("src");
			this.file = this.original.split(".");
			this.file[1] = "-hover.png";
			this.file = this.file.join("");
			$([this.file]).preload();

			$(this).hover(function() {
				$(".img, .rowimg", this).attr("src", this.file);
				$("a", this).css("color", "#cf5545");
				$(".info", this).fadeTo("fast", "0.9");
			}, function() {
				$(".img, .rowimg", this).attr("src", this.original);
				$("a", this).css("color", "#555");
				$(".info", this).fadeOut("fast");
			});
		});
		var $gallery = $('a[rel=gallery]').colorbox({
			opacity : 0.5
		});
		$('a#gallery').click(function(e) {
			e.preventDefault();
			$gallery.eq(0).click();
		});
		var $accesorios = $('a[rel=accesorios]').colorbox({
			opacity : 0.5
		});
		$('a#accesorios').click(function(e) {
			e.preventDefault();
			$accesorios.eq(0).click();
		});
		if(document.page == "productos") {
			$(".up").hide();
			altotexto = $("#productotext").css("height");
			altocontenedor = $("#productwrapper").css("height");
			if(altotexto <= altocontenedor + 10) {
				$(".down").hide();
			}
		}

	}
}

function activateProductos(ac) {
	$("#productoMenu").click(function() {menudesp()
	});
	if(ac != 0) {menudesp();
	}
}

function godown() {
	if(document.going == 0) {
		document.going = 1
		altotexto = $("#productotext").css("height");
		margentexto = $("#productotext").css("marginTop");
		altocontenedor = $("#productwrapper").css("height");
		margentexto = parseInt(margentexto.slice(0, margentexto.length - 2));
		altocontenedor = parseInt(altocontenedor.slice(0, altocontenedor.length - 2));
		altotexto = parseInt(altotexto.slice(0, altotexto.length - 2));

		if(altotexto + margentexto - altocontenedor > altocontenedor) {
			newmargin = -margentexto + altocontenedor - 10;
		} else {
			newmargin = altotexto - altocontenedor + 10;
			$(".down").hide();
		}
		if(newmargin != 0) {
			$("#productotext").animate({
				marginTop : -newmargin + "px"
			}, 500, function() {
				document.going = 0
			});
			if(! $(".up").is(":visible")) {
				$(".up").show();
			}
		} else {
			document.going = 0
		}
	}
}

function goup() {
	if(document.going == 0) {
		document.going = 1
		altotexto = $("#productotext").css("height");
		margentexto = $("#productotext").css("marginTop");
		altocontenedor = $("#productwrapper").css("height");
		margentexto = parseInt(margentexto.slice(0, margentexto.length - 2));
		altocontenedor = parseInt(altocontenedor.slice(0, altocontenedor.length - 2));
		altotexto = parseInt(altotexto.slice(0, altotexto.length - 2));

		if(margentexto + altocontenedor < 0) {
			newmargin = margentexto + altocontenedor - 10;
		} else {
			newmargin = 0;
			$(".up").hide();
		}
		if(margentexto != 0) {
			$("#productotext").animate({
				marginTop : newmargin + "px"
			}, 500, function() {
				document.going = 0
			});
			if(! $(".down").is(":visible")) {
				$(".down").show();
			}
		} else {
			document.going = 0
		}
	}
}

function reqContact(conturl) {
	repairBlack();
	centerLoad();
	$("#contactBlack").fadeTo(500, 0.6);
	if($("#contactForm").length) {
		closeForm(1);
	}
	$.ajax({
		url : conturl,
		success : function(e) { appendContact(e)
		}
	});
}

function centerLoad() {
	var margin = $(window).height() / 2;
	$('.centerload').css('margin-top', margin);
}

function appendContact(html) {
	$("body").append(html);
	$("#contactForm").fadeIn("fast", function() {
		$('.form').jqTransform({
			
			imgPath : '/static/js/img/'
		});
		$(".cerrar").click(function() {closeForm(0)
		});
		if($("#a").length) {
			$("#a").click(function() {addNewJob("experiencia")
			});
			document.jobs = 1;
		}
		jsonAjax();
		repairBlack();
	});
}

function repairBlack() {
	h = $('#topblue').height() + $('#footer').height() + 50;
	hmore = $("#contactForm").height() + 90;
	if(h < hmore) {
		h = hmore
	};
	$('#contactBlack').css({
		height : h + "px"
	});
}
function jsonAjax() {
	$(".form").submit(function(e) {
		countGAsend($(".urlGA").attr("value"));
		sendForm(e);
	});
	if($("#map").length != 0) {googlemapsload();
	}
	if($('.categoriaP').length != 0) {
		$(".activateprod").click(function() {
			$(this).parent().parent().parent().find("table").toggle(150, function() { repairBlack()
			});
		});
	}
	if($(".antecedente").length != 0) {
		$(".antecedente:last").css("display", "none");
		$("#agregar").click(function() { addExp()
		})
	}
}

function sendForm(e) {
	e.preventDefault();
	var contact_f = $(".form form")
	repairBlack();
	centerLoad();
	$("#contactBlack").fadeTo(500, 0.6);
	if($("#contactForm").length) {
		closeForm(1);
	}
	$.ajax({
		url : contact_f.attr('action'),
		type : contact_f.attr('method'),
		data : contact_f.serialize(),
		success : function(e) { appendContact(e)
		}
	});
}

function closeForm(d) {
	$("#contactForm").fadeOut(0, function() {$(this).remove()
	});
	if(d == 0) {
		$("#contactBlack").fadeOut();
	}
}

$.fn.preload = function() {
	this.each(function() {
		$('<img/>')[0].src = this;
	});
}
function googlemapsload() {
	var myOptions = {
		zoom : 12,
		center : new google.maps.LatLng(-31.714478, -60.781302),
		mapTypeId : google.maps.MapTypeId.ROADMAP
	}
	var map = new google.maps.Map(document.getElementById("map"), myOptions);

	var image = '/static/img/soticonlyicon.png';
	var FirstLatLng = new google.maps.LatLng(-31.714478, -60.781302);
	var SecondLatLng = new google.maps.LatLng(-31.644102, -60.703854);
	var ThirdLatLng = new google.maps.LatLng(-32.95746, -60.683179);
	var beachMarker1 = new google.maps.Marker({
		position : FirstLatLng,
		map : map,
		icon : image
	});
	var infowindow1 = new google.maps.InfoWindow({
		content : "<div style='font-size: 13px; width: 300px'><p><b>Administración y Fábrica</b></p><p>Calle 9 - Parque Industrial Sauce Viejo</p><p>(3017) Sauce Viejo - Santa Fe - Argentina</p><p>Tel.Fax.: +54 0342 499 6301</p><p>info@sotic.com.ar</p></div>"
	});
	var beachMarker2 = new google.maps.Marker({
		position : SecondLatLng,
		map : map,
		icon : image
	});
	var infowindow2 = new google.maps.InfoWindow({
		content : "<div style='font-size: 13px; width: 300px'><p><b>SOTIC S.A. - Local comercial</b></p><p>Rivadavia 2771</p><p>Tel/fax: (+54 342) 4556337</p></div>"
	});
	var beachMarker3 = new google.maps.Marker({
		position : ThirdLatLng,
		map : map,
		icon : image
	});
	var infowindow3 = new google.maps.InfoWindow({
		content : "<div style='font-size: 13px; width: 300px'><p><b>SOTIC S.A. - Local comercial</b></p><p>Av. Pte. Perón 4051 (ex av. Godoy)</p><p>Tel: (+54 341) 4332225</p></div>"
	});
	google.maps.event.addListener(beachMarker1, 'click', function() {
		infowindow1.open(map, beachMarker1);
	});
	google.maps.event.addListener(beachMarker2, 'click', function() {
		infowindow2.open(map, beachMarker2);
	});
	google.maps.event.addListener(beachMarker3, 'click', function() {
		infowindow3.open(map, beachMarker3);
	});
	$("#open1").click(function() { map.setCenter(FirstLatLng)
	});
	$("#open2").click(function() { map.setCenter(SecondLatLng)
	});
	$("#open3").click(function() { map.setCenter(ThirdLatLng)
	});
}

function addExp() {
	nuevo = $(".antecedente:last");
	clon = $(nuevo).clone();
	$("#jobs").append(clon);
	actval = $("#id_experiencia-TOTAL_FORMS").attr("value");
	$("#id_experiencia-TOTAL_FORMS").attr("value", parseInt(actval) + 1);

	$(clon).find("label").each(function() {
		cadenafor = $(this).attr("for").split("-");
		cadenafor[1] = parseInt(cadenafor[1]) + 1;
		$(this).attr("for", cadenafor.join("-"));
	});
	$(clon).find("input,textarea").each(function() {
		cadenaid = $(this).attr("id").split("-");
		cadenaid[1] = parseInt(cadenaid[1]) + 1;
		$(this).attr("id", cadenaid.join("-"));
		cadenaname = $(this).attr("name").split("-");
		cadenaname[1] = parseInt(cadenaname[1]) + 1;
		$(this).attr("name", cadenaname.join("-"));
	});
	$(nuevo).show(function() { repairBlack();
	});
}

