var nSl;
var cSl;
var target;
var firstLoad;
var cImg;
var prevImg;
var slideTime = 2000;//miliseconds
//onResize function
$(window).resize(function(){
    target = ($(window).width() - 967) / 2;
    $("#slider .slide").css({
        left: $(window).width()
    });
    $("#slider .slide:eq(" + cSl + ")").css({
        left: target
    });
    $("#featured #laptop2").css({
        left: target - 82
    });
    
    
});

//Main function
$(function(){
    cSl = 0;
    nSl = $("#slider .slide").length;
    // LIGHTBOX
    if ($("a[rel^='prettyPhoto']").length != 0) {
        $("a[rel^='prettyPhoto']").prettyPhoto({
            theme: 'dark_square' /* light_rounded / dark_rounded / light_square / dark_square / facebook */
        });
    };
    //lazy load
    if ($("#port1 img").length != 0) {
        $("#port1 img").lazyload({
            effect: "fadeIn",
            effectspeed: 2000
        });
    }
    
    //MENU
    if ($("#menu .active").length != 0) {
        $('<div id="navi-pad"></div>').css({
            width: $('#menu img.active').width(),
            left: $("#menu img.active").position().left
        }).appendTo('#menuwrap');
    } else {
		$('<div id="navi-pad"></div>').css({
            width: 50,
            left: -50
        }).appendTo('#menuwrap');
	}
    $("#menu").animate({
        top: 0
    });
    // HOVER
    $("#menu img").not(".active").hover(function(){
        $(this).attr("src", $(this).attr("src").split(".").join("-ov."));
        $('#navi-pad').stop(true).animate({
            width: $(this).width() + 0,
            left: $(this).position().left
        }, {
            duration: 1000,
            easing: 'easeOutElastic',
            queue: false
        });
    }, function(){
        $(this).attr("src", $(this).attr("src").split("-ov.").join("."));
		var restWidth= ($("#menu .active").length != 0) ? $('#menu img.active').width() : 50;
		var restLeft= ($("#menu .active").length != 0) ? $('#menu img.active').position().left : -50;
        $('#navi-pad').stop(true).animate({
            width: restWidth,
            left: restLeft
        }, {
            duration: 1000,
            easing: 'easeOutElastic',
            queue: false
        });
    });
    //buttons
    $(".hover").hover(function(){
        $(this).attr("src", $(this).attr("src").split(".").join("-ov."));
    }, function(){
        $(this).attr("src", $(this).attr("src").split("-ov.").join("."));
    })
    //SLIDER
    //console.log ($("#slider .slide").length)
    target = ($(window).width() - 967) / 2;
    $("#slider .slide:first").css("left", target);
    $("#slider .slide:gt(0)").css("left", $(window).width());
    setInterval(nextSl, 8000);
    //BOXES heights
    $(".box p").each(function(index){
        $(this).css("height", $(this).parent().parent().height() - 192);
    });
    //BOXES LINKS
    $("body:not(.content) .box").click(function(){
        window.location = $(this).find("a").attr("href");
        return false;
    });
    //BOXES ARROWS
    if (jQuery.support.opacity) {
        //FF oOPERA ETC
        $(".arrow").css({
            opacity: 0
        });
        $("body:not(.content) .box").hover(function(){
            $(this).find(".arrow").stop(true).animate({
                left: 170,
                opacity: 1
            })
        }, function(){
            $(this).find(".arrow").stop(true).animate({
                left: 270,
                opacity: 0
            })
        })
    }
    else {
        //IE
	$(".arrow").css({
            left: 330
        });
        $("body:not(.content) .box").hover(function(){
            $(this).find(".arrow").stop(true).animate({
                left: 170
            })
        }, function(){
            $(this).find(".arrow").stop(true).animate({
                left: 330
            })
        })
    }
    //RIGHT COLUMN
    var newH = $("#rightcol p:eq(1)").height() + ($("#boxes").height() - $("#rightcol").height()) - 81;
    $("#rightcol p:eq(1)").css("height", newH);
    
    
    // form validation
    if ($("#contactForm").length != 0) {
        $('#contactForm').validate({
			rules: { 
				name1 : { required : true, minlength: 5 },
				firma : { required : true, minlength : 5},
				email : { required : true, email : true},
				nachricht : {required : true}
				},
			errorPlacement: function(error, element) {
				//console.log(error.text())
				if(error.text()!= "") {
					element.next().removeClass("valid").addClass("invalid").show();
					element.next().next().text(error.text()).show();
				} else {
					element.next().next().hide();
					element.next().removeClass("invalid").addClass("valid").show();
				}
	 			
   			},
			success:function(){
				//do nothing - required by erroplacemnt, do not remove
			},
			messages:{
				name1: {
					required: "Bitte Ihren Vor- und Nachnamen angeben.",
					minlength: "Das scheint ein sehr kurzer Name zu sein?"
				},
				firma: {
					required: "Bitte geben Sie den Namen Ihrer Firma an.",
					minlength: "Das scheint ein sehr kurzer Firmen-Name zu sein?"
				},
				email: {
					required: "Um Sie zu kontaktieren bauche ich Ihre E-Mail Adresse.",
					email: "Bitte eine gültige E-Mail Adresse angeben."
				},
				nachricht: {
					required : "Ich bin gespannt auf Ihre Nachricht!"
				}
			},
			submitHandler: function(form) {
				//console.log('submitting');
				$("#contactFormDiv").slideUp()
				//$("#submitting").slideDown()
			
				$(form).ajaxSubmit({
					success: function(responseText) {
						if(responseText == "Message Sent") {
							$("#submitSuccess").slideDown();
						} else {
							$("#submitError").slideDown();
						}
						
					},
					error: function() {
						//$("#submitting").slideUp();
						$("#submitError").slideDown();
					} 
				});
			}

        });//end validate
	
	
	// TELEFON LIGHTBOX
	$('#kontaktTelefon a').click(function(e) {
		// hide scrollbars!
		$('body').css('overflow-y', 'hidden');
		$('<div id="mylightbox"></div>')
			.css('top', $(document).scrollTop())
			.css('opacity', '0')
			.animate({'opacity': '0.5'}, 'slow')
			.appendTo('body');
		$('<div id="mylightbox_container"></div>')
			.hide()
			.appendTo('body');
		$('<img />')
			.attr('src', $(this).attr('href'))
			.load(function() {
				positionLightboxImage();
			})
			.click(function() {
				removeLightbox();
			})
			.appendTo('#mylightbox_container');
		return false;
	});//end telefon lightbox
    $("#kontaktEmail").html('<a href="mailto:chris@mcneely.ch">Email senden</a>');
	}//end if contactform
    
    
});
//FUNCTIONS
function nextSl(){
    var next = (cSl + 1 < nSl) ? (cSl + 1) : 0;
    //console.log(next);
    $("#slider .slide:eq(" + cSl + ")").animate({
        left: -1045
    }, {
        complete: function(){
            $(this).css("left", $(window).width())
        }
    })
    $("#slider .slide:eq(" + next + ")").animate({
        left: target
    })
    cSl = next;
}

//
function rotatePics(currentPhoto){
    var numberOfPhotos = $('#laptop2 img').length;
    currentPhoto = currentPhoto % numberOfPhotos;
    
    $('#laptop2 img').eq(currentPhoto).fadeOut(function(){
        // re-order the z-index
        $('#laptop2 img').each(function(i){
            $(this).css('zIndex', ((numberOfPhotos - i) + currentPhoto) % numberOfPhotos);
        });
        $(this).show();
        setTimeout(function(){
            rotatePics(++currentPhoto);
        }, slideTime);
    });
}
function positionLightboxImage(){
	var top = ($(window).height() - $('#mylightbox_container').height()) / 2;
	var left = ($(window).width() - $('#mylightbox_container').width()) / 2;
	
	$('#mylightbox_container').css({
		'top': top + $(document).scrollTop(),
		'left': left
	}).fadeIn();
}
function removeLightbox(){
	$('#mylightbox, #mylightbox_container').fadeOut('slow', function(){
		$(this).remove();
		$('body').css('overflow-y', 'auto'); // show scrollbars!
	});
}

$(window).load(function () {
  //FEATURED macbook
    if ($("#featured").length != 0) {
		var numberOfPhotos = $('#laptop2 img').length;
		$('#laptop2 img').each(function(i){
            $(this).css('zIndex', (numberOfPhotos - i)  % numberOfPhotos);
        });
		

        $("#featured #laptop2").animate({
            left: target - 82
        }, {
            duration: 3500,
			complete: function() {
				if (slidesArr && !firstLoad) {
					//rotatePics(0);
					firstLoad = true;
					loadPic(0);
				}
			}
        }
		
		
		);//end animate
        
        
    }//end if
});//end window.load


function loadPic(ind){
	prevImg = cImg;
	cImg = $('<img src="images/slides/' + slidesArr[ind] + '" />');
	var numberOfPhotos = slidesArr.length;
	cImg.appendTo($('#laptop2')).hide(); //.css('zIndex', ((numberOfPhotos - ind - 2)) % numberOfPhotos);
	cImg.load(function(){
		$(this).fadeIn(function(){
			if (ind + 1 >= slidesArr.length && slidesArr.length>1) {
				//rotate
				$('#laptop2 img').each(function(i){
					$(this).css('zIndex', ((numberOfPhotos - i) + ind - 1) % numberOfPhotos);
				});
				setTimeout(function(){
					rotatePics(numberOfPhotos - 1);
				}, slideTime);
			}
			else if (ind + 1 < slidesArr.length) {
				//load
				setTimeout(function(){
					loadPic(++ind);
				}, slideTime);
			}
		});
		
		
	});
	
	
}










