﻿/* Saants www.saants.es                                            */
/* Version 4.0                                                     */
/*                                                                 */
/* Doubts about this code? send us an e-mail to saants@saants.es   */
/* Have a good day!                                                */

var Partes;
var PrimNiv = 0;
var winW = 0; var winH = 0;var Moving = false;
var Webkit = false; var iPad = false; var Chrome = false;
var CurrentId = 0;var currOrient = 0;
var linkFB = 'https://graph.facebook.com/151955384837101/feed?access_token=176530302259|d7c9e5a833b5b18875c1faec.1-666227546|SDQlzPx4CfYI3auIi4KML3kn2cE&limit=3&callback=?';
var linkTW = 'http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=saantsdi&count=3';
var tweets = new Array(); var curr_tweet = -1; var olProy;var arrImgs = new Array();var currImgProj = 0;
var intervAvatar; var Avatar = 0; var arrAvatares = new Array();
var projVis = new Array(); var olMT = 0;var PYCont = 0;

$(document).ready(function () {

    var deviceAgent = navigator.userAgent.toLowerCase();
    Webkit = deviceAgent.match(/(webkit)/);
    iPad = deviceAgent.match(/(ipad|iphone|ipod)/);
    Chrome = deviceAgent.match(/(chrome)/);

    LocationHash();
    getTwitter();

    PonerMenuEnHome();
    ResizeDivs();
    ActivarLinks();
    VerProyectoDetalles();

    if (window.DeviceMotionEvent != undefined) {
        window.ondevicemotion = function (event) {
            if (currOrient != window.orientation) {
                ResizeDivs();
                currOrient = window.orientation;
            }
        }
    }

    arrAvatares = $(".ulAvatars li");
    //Avatar = Math.floor(Math.random() * arrAvatares.length);
    $(arrAvatares[Avatar]).fadeIn(800);

    FeedFacebook();

    window.fbAsyncInit = function () {
        nombreFB = false;

        FB.init({ appId: '146427545448931', status: true, cookie: true, xfbml: true, oauth: false });

        /*FB.getLoginStatus(function (response) {

            if (response.authResponse) {
                $("#nombre").html("<em>" + response.first_name + "</em>: ");
                nombreFB = true;
            }

        });

        if (!nombreFB) {
            FB.api('/me', function (response) {
                if (response.name != undefined) {
                    $("#nombre").html("<em>" + response.first_name + "</em>: ");
                }
            });
        }     */

    };

    (function () {
        var e = document.createElement('script'); e.async = true;
        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        document.getElementById('fb-root').appendChild(e);
    } ());

    PreloadImgs();
});



/* Secciones ****************************************** */

$(window).resize(function () {
    ResizeDivs();
});

function LocationHash() {
    Partes = $(".cssParte");

    if (location.hash != "") {

        var Nivs = $("#MainMenuContainer #ulMenu li");

        Nivs.each(function (ind, opc) {
            var hh = $("a", opc).attr("href");
            if (location.hash == hh) {
                GoToSection(ind);
                return false;
            }
        });
    }
}

function PonerMenuEnHome() {
    $("#MenuHome").css("display", "none");
    $("#MenuHome").html($("#Menu").html());
    $("#MenuHome").fadeIn();
}

function ResizeDivs() {
    winW = $(window).width();
    winH = $(window).height();

    Partes.each(function (indice, opcion) {
        $(opcion).width(winW);
        $(opcion).height(winH);
    });

    var ttop = winH - 90 - 37; /* Height del menu = 90, height de la transparencia = 37 */
    $("#divTransparenciaMore").css("top", ttop);

};

function ActivarLinks() {
    var Nivs = $("#MenuHome #ulMenu li");
    Nivs.each(function (indice, opcion) {
        if ($(opcion).data("level").length == "4") {
            PrimNiv++;
            $(opcion).click(function () {
                GoToSection(indice);
                return false;
            });
        };
    });

    var Nivs = $("#Menu #ulMenu li");
    Nivs.each(function (indice, opcion) {
        if ($(opcion).data("level").length == "4") {
            PrimNiv++;
            $(opcion).click(function () {
                GoToSection(indice);
                return false;
            });
        };
    });

};

function GoToSection(id) {

    if (id == CurrentId || Moving) return;

    //Finalizar
    switch (CurrentId) {
        case 1: clearInterval(intervAvatar); break;
    }

    $("#divTransparenciaMore").css("display", "hidden");

    //Show-Hide
    Moving = true;

    $(Partes[CurrentId]).fadeOut(600);

    if (id == 0) {
        $("#MainMenuContainer").fadeOut();
        $("#MenuHome li").each(function (indice3, opcion3) {
            if (indice3 == id) {
                $(opcion3).addClass("selected");
                location.hash = $("a", opcion3).attr("href");
            } else {
                $(opcion3).removeClass("selected");
            }
        });
    }
    else 
    {
        $("#Menu li").each(function (indice2, opcion2) {
            if (indice2 == id) {
                $(opcion2).addClass("selected");
                location.hash = $("a", opcion2).attr("href");
            } else {
                $(opcion2).removeClass("selected");
            }
        });

    }

    setTimeout(function () {
        Moving = false;

        $(Partes[id]).fadeIn(900);

        if (id != 0 && CurrentId == 0) {
            $("#MainMenuContainer").fadeIn();
        };
        CurrentId = id;
    }, 900);

    //Iniciar
    switch (id) {

        case 1: IniciarAvatares(); break;
        case 2: MostrarUpDownProyectos(); break;
            
    }


};

/* Agencia */

function IniciarAvatares() {
    intervAvatar = setInterval("ReelAvatares()", 10000);
}

function ReelAvatares() {
    $(arrAvatares[Avatar]).fadeOut(800);
    Avatar++;
    if (Avatar > arrAvatares.length - 1) { Avatar = 0; }
    setTimeout(function () { $(arrAvatares[Avatar]).fadeIn(800); }, 800);

    

};

/* Work */

function MostrarUpDownProyectos() {

    var HH = $(".olProyectos").height() + $(".olProyectos").position().top;
    var MaxH = winH - $(".olProyectos").position().top;
    var Calc = HH + 150;
    
    //console.log("HH = " + HH + ", MaxH = " + MaxH + ", Calc = " + Calc);

    if (Calc > MaxH) {
        $("#divTransparenciaMore").fadeIn();
    }

};

function DesplazarProyectosUpDown(dir) {
    var HH = $(".olProyectos").height() + $(".olProyectos").position().top;
    var MaxH = winH - $(".olProyectos").position().top;
    var Calc = 0;

    if (dir < 0) {
        Calc = HH + olMT + 150;
        //console.log("HH = " + HH + ", olMT = " + olMT + ", MaxH = " + MaxH + ", Calc = " + Calc);
        if (Calc > MaxH) {
            olMT = olMT - 200;
            if ((Calc - 200) < MaxH) { $("#divTransparenciaMore_D").removeClass("activ"); }
            $("#divTransparenciaMore_U").addClass("activ");
        }
        else {
            
            return;
        } 
    }
    else {
        if (olMT < 0) {
            olMT = olMT + 200;
            if (olMT == 0) { $("#divTransparenciaMore_U").removeClass("activ"); }
            $("#divTransparenciaMore_D").addClass("activ");
        } else {
            return; 
        } 
    }
    $(".olProyectos").stop().animate({ marginTop: olMT }, 500);


}

function VerProyectoDetalles() {

    $("#divTransparenciaMore_D").click(function () { DesplazarProyectosUpDown(-1) });
    $("#divTransparenciaMore_U").click(function () { DesplazarProyectosUpDown(+1) });

    PYCont = $("#ProyContainer").height();
    olProy = $(".olProyectos li");
    olProy.each(function (indice, opcion) {

        //Mostrar explicación de proyecto
        $(opcion).bind("mouseover", function () {
            var mpy = $(this).position().top;
            var spl = $("span", this).height();
            if (mpy > (spl - 40)) {
                $("span", this).css("top", mpy - spl);
            } else {
                $("span", this).css("top", -10);
            }
        });

        //Ver un proyecto
        $(opcion).click(function () {
            $(".olProyectos").slideUp(500);
            $("#divTransparenciaMore").fadeOut();
            $("#MainMenuContainer").fadeOut();
            setTimeout(function () {
                $("#divShowP").fadeIn(1000);

                var proyNombre = $("h3", opcion).html();
                var h1 = "/ " + proyNombre;
                if ($(opcion).data("link") != "") { h1 += " / <a target='_blank' href='" + $(opcion).data("link") + "'>ir</a>" };
                $("#h1Proj").html(h1);

                var imgs = $(opcion).data("imgs");
                arrImgs = imgs.split(","); var lis = "";
                for (var i = 0; i < arrImgs.length; i++) {
                    lis += "<li><img src='/_includes/projects/" + arrImgs[i] + "' alt='" + proyNombre + "' /></li>";
                }
                $("#ulProjectImages").html(lis);
                currImgProj = 0;
                $("#ulProjectImages").css("marginLeft", "0");
                $("#arrowLeft").css("display", "none");
                $("#arrowRight").css("display", "block");

            }, 800);
        });
    });

    // Cerrar un proyecto
    $("#arrowClose").click(function () {
        $("#divShowP").fadeOut(1000);
        setTimeout(function () {
            $(".olProyectos").slideDown(500);
            $("#MainMenuContainer").fadeIn();
            setTimeout(function () {
                MostrarUpDownProyectos();
            }, 500);

        }, 1000);
    });

    //Control flechas
    $("#arrowLeft").click(function () {
        if (currImgProj > 0) {
            currImgProj--;
            $("#ulProjectImages").animate({ marginLeft: -currImgProj * 710 }, 500);
            if (currImgProj < (arrImgs.length - 1)) { $("#arrowRight").fadeIn() }
            if (currImgProj == 0) { $("#arrowLeft").fadeOut() }
        }
    });
    $("#arrowRight").click(function () {
        if (currImgProj < arrImgs.length - 1) {
            currImgProj++;
            $("#ulProjectImages").animate({ marginLeft: -currImgProj * 710 }, 500);
            if (currImgProj == (arrImgs.length - 1)) { $("#arrowRight").fadeOut() }
            if (currImgProj > 0) { $("#arrowLeft").fadeIn() }
        }
    });

};



/* Redes Sociales *********************************** */

function getTwitter() {

    $.getJSON(linkTW + "&callback=?",
            function (data) {
                var nHtml = "";
                $.each(data, function (ind, item) {
                    var tit = item['text'];
                    tweets.push(tit.parseURL().parseUsername());
                });

            }).success(function () { rotateTwitter();  setInterval("rotateTwitter()", 15000); });

        };

        function rotateTwitter() {
            curr_tweet++; if (curr_tweet >= tweets.length) { curr_tweet = 0; }
            $(".twCont").fadeOut(800);
            setTimeout(function () {
                $("#twitter1").html(tweets[curr_tweet]);
                $("#twitter2").html(tweets[curr_tweet]);
                $(".twCont").fadeIn(800);
            }, 750);
        };


function FeedFacebook() {
    if ($("#lastFB").length == 0) { return }
    var statusHTML = ""; var FirstHTML = "";
    $.getJSON(linkFB,
		function (json) {
		    if (json.data == undefined) return;
		    var fbs = json.data;
		    for (var i = 0; i < fbs.length; i++) {

		        var txt = fbs[i].message + "";
		        var link = fbs[i].link;
		        if (link != undefined) {
		            link = "<a href='" + fbs[i].link + "' target='_blank'>" + fbs[i].name + "</a>";
		        } else {
		            link = "";
		        }
		        //if (fbs[i].type == "video") { txt = "<a href='" + fbs[i].link + "' target='_blank'>" + fbs[i].name + "</a>"; }
		        //if (fbs[i].type == "photo") { txt = "<img class='fbpict' src='" + fbs[i].picture + "' />"; }


		        if (i == 0) {
		            FirstHTML = retMax(txt, 300).parseURL() + "<br />" + link;
		        }

		    }

		    $("#lastFB").css("display", "none");
		    $("#lastFB").html(FirstHTML);
		    $("#lastFB").fadeIn();


		}
	);
};


function return2br(rep) {
    return rep.replace(/(\r\n|[\r\n])/g, "<br />");
};

function retMax(ret, maxx) {
    if (ret.length < maxx) {
        return ret;
    } else {
        return ret.substr(0, maxx) + "...";
    }
};

function time_offset(t) {
    var now = new Date();
    var tt = new Date(t);
    var diff = new Date();
    diff.setTime(now.getTime() - tt.getTime());
    var o = Math.round(diff.getTime() / 1000);

    switch (true) {
        case (o <= 1): return "just now"; break;
        case (o < 20): return o + " seconds ago"; break;
        case (o < 40): return "half a minute ago"; break;
        case (o < 60): return "less than a minute ago"; break;
        case (o <= 90): return "1 minute ago"; break;
        case (o <= 59 * 60): return Math.round(o / 60) + " minutes ago"; break;
        case (o <= 60 * 60 * 1.5): return "1 hour ago"; break;
        case (o <= 60 * 60 * 24): return Math.round(o / 60 / 60) + " hours ago"; break;
        case (o <= 60 * 60 * 24 * 1.5): return "1 day ago"; break;
        case (o < 60 * 60 * 24 * 7): return Math.round(o / 60 / 60 / 24) + " days ago"; break;
        case (o <= 60 * 60 * 24 * 9): return "1 week ago"; break;
        default: return tt.format("mmm dd");
    }
};

String.prototype.parseURL = function () {
    return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function (url) {
        return "<a href='" + url + "' target='_blank'>" + url + "</a>";
    });
};

String.prototype.parseUsername = function () {
    return this.replace(/[@]+[A-Za-z0-9-_]+/g, function (u) {
        var username = u.replace("@", "");
        return "<a href='http://twitter.com/" + username + "' target='_blank'>@" + username + "</a>";
    });
};

/* Extras */


/* Extras */

function PreloadImgs(){
    var cache = []; var nomImgs = ""; 
    olProy.each(function (indice, opcion) {
        nomImgs+= $(opcion).data("imgs") + ",";
    });

    var arrImgs = nomImgs.split(",");
    var args_len = arrImgs.length - 1;

    for (var i = 0; i < args_len; i++) {
      var cacheImage = document.createElement('img');
      cacheImage.src = "/_includes/projects/" + arrImgs[i];
      cache.push(cacheImage);
    }
};

function getCount(part, lang) {
    var vis = false;
    var idd = $(part).data("idd");
    for (var i = 0; i < projVis.length; i++) {
        if (idd = projVis[i]) vis = true;
    }
    if (!vis) {
        projVis.push(idd);
        var proj = $("h3", part).html();
        _gaq.push(['_trackEvent', 'Work', proj, lang]);
    }

}
