﻿/* ------------------------------------------------------------------------
	s3Slider
	
	Developped By: Boban KariÅ¡ik -> http://www.serie3.info/
        CSS Help: MÃ©szÃ¡ros RÃ³bert -> http://www.perspectived.com/
	Version: 1.0
	
	Copyright: Feel free to redistribute the script/modify it, as
			   long as you leave my infos at the top.
------------------------------------------------------------------------- */


(function($){  

    $.fn.s3Slider = function(vars) {       
        
        var element     = this;
        var timeOut     = (vars.timeOut != undefined) ? vars.timeOut : 4000;
        var current     = null;
        var timeOutFn   = null;
        var faderStat   = true;
        var mOver       = false;
        var items       = $("#" + element[0].id + "Content ." + element[0].id + "Image");
        //var itemsSpan   = $("#" + element[0].id + "Content ." + element[0].id + "Image span");
            
        /*items.each(function(i) {
    
            $(items[i]).mouseover(function() {
               mOver = true;
            });
            
            $(items[i]).mouseout(function() {
                mOver   = false;
                fadeElement(true);
            });
            
        });*/
        
        var fadeElement = function(isMouseOut) {
            var thisTimeOut = (isMouseOut) ? (timeOut/2) : timeOut;
            thisTimeOut = (faderStat) ? 10 : thisTimeOut;
            if(items.length > 0) {
                timeOutFn = setTimeout(makeSlider, thisTimeOut);
            } else {
                console.log("Poof..");
            }
        }
        
        var makeSlider = function() {
            current = (current != null) ? current : items[(items.length-1)];
            var currNo      = jQuery.inArray(current, items) + 1
            currNo = (currNo == items.length) ? 0 : (currNo - 1);
            var newMargin   = $(element).width() * currNo;
            if(faderStat == true) {
                if(!mOver) {
                    $(items[currNo]).fadeIn((timeOut/6), function() {
                        /*if($(itemsSpan[currNo]).css('bottom') == 0) {
                            $(itemsSpan[currNo]).slideUp((timeOut/6), function() {
                                faderStat = false;
                                current = items[currNo];
                                if(!mOver) {
                                    fadeElement(false);
                                }
                            });
                        } else {
                            $(itemsSpan[currNo]).slideDown((timeOut/6), function() {*/
                                faderStat = false;
                                current = items[currNo];
                                if(!mOver) {
                                    fadeElement(false);
                                }
                         /*   });
                        }*/
                    });
                }
            } else {
                if(!mOver) {
                    /*if($(itemsSpan[currNo]).css('bottom') == 0) {
                        $(itemsSpan[currNo]).slideDown((timeOut/6), function() {
                            $(items[currNo]).fadeOut((timeOut/6), function() {
                                faderStat = true;
                                current = items[(currNo+1)];
                                if(!mOver) {
                                    fadeElement(false);
                                }
                            });
                        });
                    } else {
                        $(itemsSpan[currNo]).slideUp((timeOut/6), function() {*/
                        $(items[currNo]).fadeOut((timeOut/6), function() {
                                faderStat = true;
                                current = items[(currNo+1)];
                                if(!mOver) {
                                    fadeElement(false);
                                }
                            });
                        /*});
                    }*/
                }
            }
        }
        
        makeSlider();

    };  

})(jQuery);  

var docW, docH, totImg = 0, baseUrl = "http://www.fabiosanvito.com/", isBig = undefined, resizeTO_id = 0, isMobile = false, wThumb = 280;
preloadImg = [new Image(), new Image(), new Image(), new Image(), new Image(), new Image(), new Image(), new Image(), new Image(), new Image()];
preloadImg[0].src = "left.png";
preloadImg[1].src = "right.png";
preloadImg[2].src = "preload.gif";
preloadImg[3].src = "kid2.png";
preloadImg[4].src = "man2.png";
preloadImg[5].src = "personal2.png";
preloadImg[6].src = "stilllifel2.png";
preloadImg[7].src = "woman2.png";
preloadImg[8].src = "contacts2.png";
preloadImg[9].src = "FaceBook-24x24_2.png";

var myScroll = null;
function loadedIScroll() {
    myScroll = new iScroll('left', { hScrollbar: false });
}

$(document).ready(function() {
  docW = $(document).width();
  docH = $(document).height();
  wThumb = 250;//parseInt((docW - 12 - 56) / 5);
  
  $(document).bind("contextmenu",function(e){
    return false;
  });
  
  if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
    isMobile = true;
  }
  
  if (isMobile) {
    document.addEventListener("touchmove", function(e) {
        if (isMobile && isBig != undefined) {
            e.preventDefault();
        }
    }, false);
    
    wThumb = parseInt((docW - 12 - 56) / 4);
    $("div#bottom").css("top", (docH - 32) + "px");
    $("div#left").css("height", (docH - 30 - $("div#top").height()) + "px");
    $("div#leftContacts").css("height", (docH - 30 - $("div#top").height()) + "px");
    $("div#logo").css("margin-right", "8px");
  }
  
  $("div#leftContacts").css("padding-top", (((docH - $("div#top").height() - $("div#bottom").height()) / 2) - 220) + "px");
  
  $("#s3slider").css("width", $("div#left").width() + "px").css("height", $("div#left").height() + "px");
  $(".s3sliderImage").find("img").css("height", $("div#left").height() + "px");
  $("div#s3slider").s3Slider({ timeOut: 2500 });
  
});

$(window).resize(function() {
	if (isBig != undefined) {
		docW = $(document).width();
		docH = $(document).height();
		/*
		if (resizeTO_id != 0)
			clearTimeout(resizeTO_id);
			
		resizeTO_id = setTimeout(function() { LoadImage(isBig); }, 250);
		*/
		LoadImage(isBig);
	}
});

function LoadImage(objImg) {
	isBig = objImg;
    var imgBigUrl = objImg.attr("data-big-image");
    var imgID = objImg.attr("id");
    $("div#popupImgInner").html("");
    
    p_image = new Image();
    p_image.onload = function() {
        var rappImg = (p_image.height / p_image.width);
		var hBig = (parseInt(docH / 10) * 9);
		if (hBig < p_image.height)
			p_image.height = hBig;
        p_image.width = (p_image.height / rappImg);
        
        if (p_image.width > docW) {
            var rappImg = (p_image.width / p_image.height);
            p_image.width = docW - (docW / 3);
            p_image.height = (p_image.width / rappImg);
        }
    
        var pup = $("div#popupImgInner");
        pup.hide();

        if (isMobile) {
            pup.css("top", (parseInt((( docH - p_image.height ) / 2)) + window.pageYOffset).toString() + "px");
        } else {
            pup.css("top", parseInt((( docH - p_image.height ) / 2)).toString() + "px");
        }
        pup.html('<div style="white-space:nowrap;"><img id="bigImgGoLeft" src="left.png" alt="" style="vertical-align:middle;cursor:pointer;" />&nbsp;<img id="bigImg" src="' + imgBigUrl + '" alt="" style="cursor:pointer; border:3px solid #CCCCCC; height:' + p_image.height + 'px; width:' + p_image.width + 'px; vertical-align:middle;" />&nbsp;<img id="bigImgGoRight" src="right.png" alt="" style="vertical-align:middle;cursor:pointer;" /></div>');
        pup.css("left", parseInt((( docW - (p_image.width + 110) ) / 2)).toString() + "px");

        pup.show(600);

        pup.find("img#bigImg").bind('click', function() { 
            clearBigImgEvents(pup);
            $("div#popupImg").hide(600);
            $("div#popupImgInner").html("");
			isBig = undefined;
        });
        pup.find("img#bigImgGoLeft").one('click', function() { 
            clearBigImgEvents(pup);
            pup.find("div").fadeOut(600, function() { 
                var newID = (parseInt(imgID) - 1);
                if (newID < 1)
                    newID = totImg;
                LoadImage($("#" + newID.toString())); 
            }); 
        });
        pup.find("img#bigImgGoRight").one('click', function() { 
            clearBigImgEvents(pup);
            pup.find("div").fadeOut(600, function() { 
                var newID = (parseInt(imgID) + 1);
                if (newID > totImg)
                    newID = 1;
                LoadImage($("#" + newID.toString())); 
            }); 
        });
        pup.find("img#bigImg").one('swiperight', function() { 
            clearBigImgEvents(pup);
            pup.find("div").fadeOut(600, function() { 
                var newID = (parseInt(imgID) - 1);
                if (newID < 1)
                    newID = totImg;
                LoadImage($("#" + newID.toString())); 
            }); 
        });
        pup.find("img#bigImg").one('swipeleft', function() { 
            clearBigImgEvents(pup); 
            pup.find("div").fadeOut(600, function() { 
                var newID = (parseInt(imgID) + 1);
                if (newID > totImg)
                    newID = 1;
                LoadImage($("#" + newID.toString())); 
            }); 
        });
        
    };
    p_image.src = imgBigUrl;
}
function clearBigImgEvents(p) {
    p.find("img#bigImg").unbind('click').unbind('swiperight').unbind('swipeleft');
    p.find("img#bigImgGoLeft").unbind('click');
    p.find("img#bigImgGoRight").unbind('click');
}
function LoadPage(pg) {
    var divInner = $("div#left");
    var divContacts = $("div#leftContacts");
    
    $("#s3slider").hide();
    
    try {
        myScroll.destroy();
        myScroll = null;
    } catch(exo) {;}
    
    switch(pg) {
        case "contacts":
            divInner.hide(600, function() {
                divContacts.fadeIn(600);
            });
            break;
        default:
            if (divContacts.is(":visible")) {
                divContacts.hide(600, function() {
                    $.ajax({
                        type: "GET",
                        url: baseUrl + "getimages.aspx?now=" + (new Date()).getTime(),
                        data: "cat=" + pg.toString().toUpperCase(),
                        error: function(sg,s,d) {
                            setError(d);
                        },
                        success: function(msg) {
                            var jsonMsg = jQuery.parseJSON(msg);
                            setGallery(jsonMsg);
                        }
                    });
                });
            } else {
                divInner.hide(600, function() {
                    $.ajax({
                        type: "GET",
                        url: baseUrl + "getimages.aspx?now=" + (new Date()).getTime(),
                        data: "cat=" + pg.toString().toUpperCase(),
                        error: function(sg,s,d) {
                            setError(d);
                        },
                        success: function(msg) {
                            var jsonMsg = jQuery.parseJSON(msg);
                            setGallery(jsonMsg);
                        }
                    });
                });
            }
            break;
    }
}

function setError(erT) {
    totImg = 0;
    var divInner = $("div#left");
    var divInnerInside = $("div#leftInside");
    divInnerInside.html("Si è verificato un errore durante il caricamento della gallery: " + erT);
    divInner.fadeIn(600);
}

function setGallery(jsonM) {
    var divInner = $("div#left");
    var divInnerInside = $("div#leftInside");
    
    if (jsonM.error == "") {
        totImg = jsonM.images.length;
        divInnerInside.masonry('destroy');
    
        var htmlToInner = "";
        
        for (var UU = 0; UU < jsonM.images.length; UU++) {
            htmlToInner += '<div class="imgCont" style="width:' + (wThumb-2).toString() + 'px; height:' + (wThumb-2).toString() + 'px;"><img id="' + (UU + 1).toString() + '" src="' + decodeURIComponent(jsonM.images[UU].thumb) + '" alt="" style="width:' + wThumb.toString() + 'px; height:' + wThumb.toString() + 'px;" data-big-image="' + decodeURIComponent(jsonM.images[UU].big) + '" /></div>';
        }
        divInnerInside.html(htmlToInner);
        if (!isMobile) {
		    //divInnerInside.css("padding-left", parseInt((docW - (parseInt((docW-16) / wThumb) * wThumb))) / 2);
			if (docW >= ((wThumb+6) * 6))
				divInnerInside.css("padding-left", parseInt((docW - 21 - ((wThumb+6) * 6)) / 2) + "px");
			else
				divInnerInside.css("padding-left", parseInt((docW - 21 - ((wThumb+6) * 4)) / 2) + "px");
		} else {
		    divInnerInside.css("padding-left", "14px");
		}
        divInnerInside.show();
        divInner.fadeIn(600, function() {
            setGallery2();
            if (isMobile) {
                $("div#left").css("height", divInner[0].scrollHeight.toString() + "px");
                $("div#bottom").css("top", $("div#left").height() + 150 + "px");
            }
            divInnerInside.imagesLoaded(function() {
                divInnerInside.masonry({
                    itemSelector: '.imgCont',
                    isAnimated:false,
                    animationOptions: { queue: false, duration: 1000, specialEasing: { top: 'easeInOutCubic'} }
                });
            });
            
            /*if (isMobile) {
                try {
                    document.removeEventListener('touchmove');
                } catch(exo) {;}
                //$(document).unbind('DOMContentLoaded');
                document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
                //document.addEventListener('DOMContentLoaded', function () { setTimeout(loadedIScroll, 200); }, false);
                setTimeout(loadedIScroll, 200);
            }*/
        });
    } else {
        totImg = 0;
        divInnerInside.html("Si è verificato un errore durante il caricamento della gallery: " + decodeURIComponent(jsonM.error));
        divInner.fadeIn(600);
    }
}

function setGallery2() {
    var divPhoto = $("div#left");
    if (divPhoto) {
        var imgs = divPhoto.find("img");
        $.each(imgs, function() {
            var ss = $(this);
            ss.mouseover(function() {
                ss.fadeTo(300, 0.4);
            });
            ss.mouseout(function() {
                ss.fadeTo(300, 1.0);
            });
            ss.click(function() {
				$("div#popupImg").css("right", "0px");
				$("div#popupImg").css("bottom", "0px");
				if (isMobile) {
				    $("div#popupImg").css("height", ($("div#top").outerHeight() + $("div#left").outerHeight() + $("div#bottom").outerHeight()).toString() + "px");
				}
                $("div#popupImg").show(500, function() { $("div#popupImg").css("filter", "alpha(opacity=70)"); LoadImage(ss); })
            });
        });
    }
}

function sMail(nomin, mail, ph, msg, btn) {
    btn.attr('disabled', 'disabled');

    $.ajax({
        type: "POST",
        url: baseUrl + "smail.aspx",
        data: "toM=" + mail.val() + "&toN=" + nomin.val() + "&toP=" + ph.val() + "&toMsg=" + msg.val(),
        error: function(sg,s,d) {
            $("#contactErr").html("Error: " + d);
            btn.removeAttr('disabled');
        },
        success: function(msg) {
            if (msg.substring(0, 3) == "KO:") {
                $("#contactErr").html('<br />' + msg.substring(3));
			} else {
                $("#contactErr").html('<br />Message sent!');
            }
			
            btn.removeAttr('disabled');
        }
    });
}

function setImgMenu(obj, newImg) {
    $(obj).find("img")[0].src = newImg;
}
