var front_image_max_height = 116;
var front_image_max_width = 167;

$(function() {
	$("a.popup").click(function() {
		var win = window.open($(this).attr("href"),"popup","width=500,scrollbars=yes");
		return false;
	});
	$("#but_luk_link").click(function() {
		$("#newsletter-thankyou").fadeOut(200);
	});
	$("#btn_newsletter").toggle(function() {
			$("#newsletter").fadeIn(200, function() {
				sifr_init();
			});
			return false;
		}, function() {
			$("#newsletter").fadeOut(200);
			return false;
		});
	
//	$("#newsletter").hide();
   $("#konkurrencen .form .inputs input, #newsletter .form .inputs input").placeholder();
   
   $("#fotoskole_banner").animate(
	  {
		marginLeft: '-458'
	  }, 
	  {
		duration: 2000,
		easing: 'easeOutBounce'
	  }
	);
	$(".car_blocks div.back_side").hide();

    if($('ul#cars_flip').length>0) {
		/*$('ul.car_blocks>li img[class!=to_change]').each(function() {
			$(this).attr("width",$(this).width()).attr("height",$(this).height());
		})*/
		loadNewCars(0,true);
		loadNewCars(3);
		setInterval(function() {
			setTimeout("changeFrontImage($('ul.car_blocks>li:eq(0)'))",1000);
			setTimeout("changeFrontImage($('ul.car_blocks>li:eq(1)'))",1300);
			setTimeout("changeFrontImage($('ul.car_blocks>li:eq(2)'),true)",1600);	
		}, 6000);
	}
	
	$("form").submit(function() {
		var valid = true;
		$(".iconInvalid").remove();
		$(this).find(":input, :radio, :checkbox").each(function() {
			var v = validate_field($(this));
			var o = (v.obj==undefined)? $(this).get(0) : $(v.obj).get(0);
			var t = (o.nodeName.toLowerCase()=="input")? $(o).attr("type").toLowerCase() : o.nodeName.toLowerCase();
			if (!v.valid) {
				valid = false;
				//var xOffset = (t=="input" && "|text|radio|checkbox".indexOf($(this).attr("type"))!=-1)? ($(this).attr("type")=="text")?-16:-30 : 4;
				var xOffset = -16;
				var yOffset = (String("|textarea|checkbox|").indexOf("|"+t+"|")!=-1)? 4 : (o.offsetHeight-12)/2;
				//if (v.obj!=undefined) yOffset = 0;
				var p = $(o).position();
				var cssProps = {
					'left': p.left + xOffset + 'px',
					'top': p.top + yOffset +'px'
				}
				var oIcon = $("<div class='iconInvalid invalid_"+$(this).attr("name")+"'/>").data("msg",v.msg).appendTo($(o).offsetParent()).css(cssProps).mouseover(function() {
					errorMsg($(this), $(this).data("msg"));
				}).mouseout(function() {
					errorMsg($(this));
				});	
			}
		});
		return valid;
	});
	
	$("#story-submit #description").bind("keyup change",function() {
		if(140-parseInt($(this).val().length)<0) {
			$(this).val($(this).val().substr(0,140))
		}
		$("#remaining-characters").html($("#remaining-characters").html().replace(/^[-\d]+/,140-parseInt($(this).val().length)))
		
	});
	
});

function loadNewCars(inp, firsttime) {
	$.ajax({
	  url: 'ssi/highest.php',
	  data: 'in=' + inp,
	  dataType:'json',
	  success:function(cars) {
		  if(!cars)return;
		  cars = cars.cars;
		  for(var i=0;i<3;++i) {
			var el = $('ul.car_blocks>li:eq('+i+') .cont');
			var car = cars[i];
			
			

			if(firsttime){ 
				var selector = ':not(.to_change)';
			} else {
				var selector = '.to_change';
			}
			
			
			var img_to_change = el.find('img'+selector);
			
			img_to_change.data("id",car.id);
			img_to_change.click(function() {
				var id = $(this).data("id");
				if(id) {
					location.href="index.php?page=vote&sub=view&id="+id;	
				}
			});
			
			
			img_to_change.attr("alt",car.title);
			var src = "assets/images/uploads/medium/"+car.image;
			img_to_change.css("width",car.width);
			img_to_change.css("height",car.height);
			img_to_change.css("margin-top",(front_image_max_height-car.height)/2);
			img_to_change.css("margin-left",(front_image_max_width-car.width)/2);
			img_to_change.attr("src",src);
			
			//$(img).data("img_to_change",img_to_change);
			
			/*img_to_change.load(function() {
				var img = $(this);
				img.show();
				//
				if(this.width>1 && this.height>1) {
					img.attr("width",this.width);
					img.attr("height",this.height);
					img.css("margin-top",(front_image_max_height-this.height)/2);
					img.css("margin-left",(front_image_max_width-this.width)/2);
					img.hide();
				}
			});*/
			
			
			
			el.find('div.title'+selector).text(car.title.substring(0,18));
			var ul = el.find('ul'+selector);
			ul.find("li.off").each(function() {
				$(this).removeClass('off');								
			});
			car.rating = Math.round(car.rating);
			for(var k=car.rating;k<5;k++) {
				ul.find('li:eq('+k+')').addClass('off');
			}
			
		  }
	  }
	});
}

var imgsToLoad = 6;

function changeFrontImage(th, reload) {
	var img = th.find('img[class!=to_change]');
	var img_height = parseInt(img.css("height"));
	var img_width = parseInt(img.css("width"));
	var bg_height = front_image_max_height;
	var bg_width = front_image_max_width;
	img.css("width",img_width).css("margin-top",(bg_height-img_height)/2).css("margin-left",(bg_width-img_width)/2);
	img.css("margin-top",(bg_height-img_height)/2);
	img.css("margin-left",(bg_width-img_width)/2);
	
	
	var img2 = th.find('img.to_change');
	if(img2) {
		var img2_h = parseInt($(img2).css("height"));
		var img2_w = parseInt($(img2).css("width"));
	}
	var bg = th.find('div.bg');
	
	img2.css({height:'0px',width:img2_w,marginTop:(bg_height-img2_h)/2,marginLeft:(bg_width-img2_w)/2});
	bg.stop().animate({height:'0px',marginTop:''+bg_height/2+'px'},200);
	
	
	
	
	
	
	var div = th.find('div.title[class!=title to_change]');
	div.animate({height:0,marginTop:'-'+img_height/2+'px'},200, function() {
		 var div2 = th.find('div[class=title to_change]');
		 var h = 15;
		 div2.hide().css({height:0,marginTop:'-'+img_height/2+'px'}).removeClass('to_change');
		 div.addClass('to_change').hide();
		 div2.animate({height:h+'px',marginTop:'0px'},200);
	});
	
	var ul = th.find('ul[class!=stars clearfix to_change]');
	ul.animate({height:0,marginTop:'-'+img_height/2+'px'},200, function() {
		 var ul2 = th.find('ul[class=stars clearfix to_change]');
		 var h = 15;
		 ul2.hide().css({height:0,marginTop:'-'+img_height/2+'px'}).removeClass('to_change');
		 ul.addClass('to_change').hide();
		 ul2.animate({height:h+'px',marginTop:'3px'},200);
		 
	});
	
	img.stop().animate({height:'0px'},200, function() {
		img.addClass('to_change').hide();
		//img.attr("width","").attr("height","");
		img2.removeClass('to_change');
		bg.animate({height:''+bg_height+'px',marginTop:0},200);
		img2.animate({height:''+img2_h+'px'},200);
		if(reload){
			loadNewCars(imgsToLoad);
			imgsToLoad = imgsToLoad + 3;
			if(imgsToLoad>=9)imgsToLoad = 0;
		}
	});
	
}

jQuery.validator.addMethod("requiredNotPlaceholder", function(value, element) { 
	 return !(value==='' || value === $(element).attr("placeholder"));
}, "Please specify text");


function validate_field(o) {
	var v = {valid:false, msg:""};
	var form = o.parents("div[id]:first").attr("id");
	
	
	switch($(o).attr("name")) {
		// generic
		case "name":
		case "navn":
			v.valid = ($(o).val().match(pattern.fullname))? true:false;
			v.msg = "Du skal indtaste både for- og efternavn";
			break;
		
		case "email":
			v.valid = ($(o).val().match(pattern.email))? true:false;
			v.msg = "Du skal indtaste en gyldig e-mail-adresse";
			break;
		
		case "phone":
		case "mobile":
			v.valid = ($(o).val().match(pattern.dkphone))? true:false;
			v.msg = "Det indtastede telefonnummer er ikke gyldigt";
			break;
			
		case "postal":	
		case "zip":
			v.valid = ($(o).val().match(pattern.dkzip))? true:false;
			v.msg = "Du skal indtaste et gyldigt postnummer";
			break;
			
		case "accept":
		case "confirm":
			v.valid = $(o).attr("checked");
			v.msg = "Du skal acceptere betingelserne";
			break;
		
		
		
		// upload story
		case "title":
			v.valid = ($(o).val()!="")? true:false;
			v.msg = "Du skal skrive en titel";
			break;
			
		case "description":
			v.valid = ($(o).val()!="")? true:false;
			v.msg = "Du skal skrive en beskrivelse";
			break;
			
		case "picture":
			var p = $(o).val().toLowerCase();
			v.valid = (p!="" && (p.substr(p.length-3,3)=="jpg" || p.substr(p.length-4,4)=="jpeg"))? true:false;
			v.msg = "Billedet skal være i JPEG-format";
			break;	
	
		// newsletter sign-up
		case "permission":
			if ($(o).parents("form").attr("id") != "submit-form") {
					v.valid = $(o).attr("checked");
					v.msg = "Du skal give din tilladelse til at vi sender dig e-mails";
				} else {
					v.valid = true;
				}
				break;
		default:
			v.valid = true;
			break;
	}
	return v;
}



function errorMsg(o,msg) {
	var e = ($(".errorMsg").size()>0)? $(".errorMsg") : $("<div class='errorMsg'></div>").appendTo("body");
	if (msg) {
		var cssParams = {
			left: o.offset().left+o.width()+4+'px',
			top: o.offset().top+'px'
		}
		e.html(msg).css(cssParams).show();
		//alert(parseInt(cssParams.left)+e.width());
		if (parseInt(cssParams.left)+e.width()>=$(window).width()-20) e.css("left",o.offset().left-e.width()-20+"px");
		if ($.browser.msie && parseInt($.browser.version.substr(0,1))<=6) $("body").addClass("showValidation");
	} else {
		e.hide();
		$("body").removeClass("showValidation");
	};
}

var pattern = {
	"email":			/^([\w\-\.]+)@((\[([0-9]{1,3}\.){3}[0-9]{1,3}\])|(([\w\-]+\.)+)([a-zA-Z]{2,4}))$/, // any email address
	"letters":			/^([a-zA-Z\u0080-\u00FF]+)$/, // only letters
	"lettersnumbers": 	/^([a-zA-Z\u0080-\u00FF0-9]+)$/, // will validate letters and/or numbers
	"lettersspace":		/^([a-zA-Z\u0080-\u00FF- ]+)$/, // only letters and spaces
	"numbers":			/^\d+$/, // only numbers
	"float":			/^\d+(,|\.)?(\d+)?$/, // only numbers
	"dkphone":			/^(\d{8})(.*)/,
	"dkzip":			/^(\d{4})$/, 
	"sezip":			/^(\d{3}[ ]{0,1}\d{2})$/, 
	"date": 			/^([0-2]?[1-9]|[3][0,1]{1})(\/(([1]{1}[0-2]|[0]?[1-9]))\/|\.(([1]{1}[0-2]|[0]?[1-9]))\.| (([1]{1}[0-2]|[0]?[1-9])) |-(([1]{1}[0-2]|[0]?[1-9]))-)(\d{4}|\d{2})$/, // DD[/. ]MM[/. ]YY(YY)
	"varchar":			/.+/, // At least one character
	"fullname":			/([a-zA-Z\u0080-\u00FF]{2,}) ([a-zA-Z\u0080-\u00FF]{2,})/ // First- and lastname
}

objects = document.getElementsByTagName("object");
for (var i = 0; i < objects.length; i++)
{
    objects[i].outerHTML = objects[i].outerHTML;
}


