﻿///<reference path="jquery-1.4.1-vsdoc.js" />
var pageIndex = 0;
var pageSize = 20;
var pageCacheSize = 2;

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////    START CONNECTION      //////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function register() {
    $('.loginBox').css('background', 'url(/Content/Design/RegisterBox.png) no-repeat scroll 0 0 transparent');
    $('.register').hide();
    $('.fbConnect').hide();
    $("#logForm").hide();
    $("#registerForm").fadeIn(400);
}

function disconnect(isFaceBookUser) {

    if (isFaceBookUser == "True") {
        FB.Connect.logout(
               function () { userLogout(); }
            );
    }
    else {
        userLogout();
    }
    return false;
}

function userLogout() {
    $.ajax(
        {
            type: "POST",
            url: "/Account.aspx/LogOff",
            success: function (result) {
                window.location.reload(true);
            },
            error: function (req, status, error) {
                alert('Une erreur s\' est produite lors de la déconnexion. Veuillez réessayer à nouveau.');
            }
        });
}

function validate_login() {
    $("#logForm .txt_Login span.error").remove();
    return isValidFn($("#login_username")) && isValidFn($("#login_password"));
}

function validate_register() {
    $("#registerForm .txt_Register span.error").remove();
    return isValidFn($("#register_username")) && isValidFn($("#register_firstname"))
           && isValidFn($("#register_lastname")) && isValidFn($("#register_email"))
           && isValidFn($("#register_password")) && isValidFn($("#register_confirmpassword"))
           && ($("#register_password").val() == $("#register_confirmpassword").val());
}

function validate_sendPicture() {
    $("#sendPictureBox span.error").remove();
    return isValidFn($("#send_title")) && isValidFn($("#send_tag")) && isCheckedFn($("#send_rule"));
}

function validate_searchPicture() {
    $("#searchPictureBox span.error").remove();
    return isValidFn($("#searchTxt"));
}

function isValidFn(input) {
    if (input.val() == "") {
        input.after('<span class="error">*</span>');
        return false;
    }
    return true;
}
function isCheckedFn(input) {
    if (!input.is(':checked')) {
        input.after('<span class="error">*</span>');
        return false;
    }
    return true;
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////   HOME INTERACTION     //////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


$(document).ready(function () {

    //If IE 6
    if (typeof document.body.style.maxHeight === "undefined") {
        $('.filters').supersleight();
        $('.navigation_left').supersleight();
        $('.navigation_right').supersleight();
    }

 

    //Add submit on Enter
    $("form input, form select").live('keypress', function (e) {
        if ($(this).parents('form').find('input:submit').length <= 0)
            return true;

        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $(this).parents('form').find('input:submit').focus().mousedown();
            return true;
        } else {
            return true;
        }
    });


    if ($('.photo img:visible').length < 12)
        $('.navigation_right')[0].style.visibility = 'hidden';

    $("input[type=file]").filestyle({
        image: "/Content/Design/Buttons/btn_browse.png",
        imageheight: 17,
        imagewidth: 21,
        width: 88
    });

    $i = (1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
    $(':file').MultiFile({ namePattern: '$name_$i', maxlength: 20 });
});

function zoomPreview(elmt) {
    var imgZoom = $(elmt).find('img.zoom');
    if (imgZoom.width() == 0)
        return false;
    var imgWidth = imgZoom.width();
    var imgHeight = imgZoom.height();

    imgZoom.css("left", ((150 - imgWidth) / 2).toString() + "px");
    imgZoom.css("top", ((150 - imgHeight) / 2).toString() + "px");
}

function slideLeft(elmt, isLeft) {
    var boxSlider = $('.box');
    var slideValue = 366;
    if (isLeft == "true") {
        slideValue = -slideValue;
        pageIndex = pageIndex - 1;
    }
    else {
        pageIndex = pageIndex + 1;
    }

    var marginTop = boxSlider.css("marginTop").replace("px", "");
    boxSlider.css("marginTop", marginTop - slideValue);
    marginTop = boxSlider.css("marginTop");
    var maxSize = -Math.floor(($('.photo img:visible').length - 1) / 12) * 366;
    $('.navigation_left').css('visibility', 'visible');
    $('.navigation_right').css('visibility', 'visible');
    if (marginTop.toString() == "0px")
        $('.navigation_left').css('visibility', 'hidden');
    if (marginTop.toString() == maxSize + "px")
        $('.navigation_right')[0].style.visibility = 'hidden';
    //$('.photo').show();
    showImages();
    return false;
}

function getRules() {
    $('#rule_content').load('/Home.aspx/Rules/', function () {
        var id = "#rule_dialog";

        //Get the screen height and width  
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();
        //Set height and width to mask to fill up the whole screen  
        $('#mask').css({ 'width': maskWidth, 'height': maskHeight });
        //transition effect       
        $('#mask').fadeIn(1000);
        $('#mask').fadeTo("slow", 0.8);
        //Get the window height and width  
        var winH = $(window).height();
        var winW = $(window).width();
        //Set the popup window to center  
        $(id).css('top', winH / 2 - $(id).height() / 2);
        $(id).css('left', winW / 2 - $(id).width() / 2);
        //transition effect  
        $(id).fadeIn(400);
        $(function () {
            $('.scrollContent').jScrollPane({ showArrows: true, scrollbarWidth: 7 });
        });
    });
    return false;
}

function getPicture(Id, baseUrl) {
    $('#picture_content').load('/Picture.aspx/Index/' + Id + " .pictureView", function () {
        var id = "#picture_dialog";
        //add AddThisplugin from homepage
      
        //var htmlStr = $('#addthis').html();
        //$('.addthisModal').html(htmlStr);
        //Get the screen height and width  
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();
        //Set height and width to mask to fill up the whole screen  
        $('#mask').css({ 'width': maskWidth, 'height': maskHeight });
        //transition effect       
        $('#mask').fadeIn(1000);
        $('#mask').fadeTo("slow", 0.8);
        //Get the window height and width  
        var winH = $(window).height();
        var winW = $(window).width();
        //Set the popup window to center  
        $(id).css('top', winH / 2 - $(id).height() / 2);
        $(id).css('left', winW / 2 - $(id).width() / 2);
        //set the comment defaultValue
        $('.commentArea').DefaultValue('Ecrire un commentaire', 'DefaultValueClass');
        createAddthis(Id, baseUrl);
       
        //transition effect  
        $(id).fadeIn(400);
        $(function () {
            $('.scrollcontent').jScrollPane({ showArrows: true, scrollbarWidth: 7, reinitialiseOnImageLoad :true });
        });
        
    });
    return false;
}

function createAddthis(index, baseUrl) {
    if (baseUrl == "http://www.tutesvuquandtudors.fr/" || baseUrl == "http://tutesvuquandtudors.fr/") {
        baseUrl = "http://www.tu-t-es-vu-quand-tu-dors.fr/";
    }
    var path = baseUrl + "Home.aspx/Picture/?ImageID=" + index;
    var a = document.createElement('a');
    a.setAttribute('class', 'addthis_button_compact');
    a.setAttribute('addthis:url', path);
    a.setAttribute('addthis:title', 'mon titre');
    a.setAttribute('addthis:description', 'ma description');
    a.setAttribute("onmouseover", "return addthis_open(this, '', '" + path + "', '" + baseUrl + "Home.aspx/')");
    a.setAttribute("onclick", "return addthis_sendto()");
    a.setAttribute("onmouseout", "addthis_close()");
    a.innerHTML = '<img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" />';
    $('#addthis_toolbox').append(a);
}

function showBox(box) {
   
    //Get the screen height and width  
    var maskHeight = $(document).height();
    var maskWidth = $(window).width();

    //Set height and width to mask to fill up the whole screen  
    $('#mask_boxes').css({ 'width': maskWidth, 'height': maskHeight });

    //transition effect       
    $('#mask_boxes').fadeIn(100);

    if ($(box).css('display') == 'none') {
        $(box).fadeIn(200);
    } else {
        $(box).fadeOut("slow");
    }

    //if mask is clicked
    $('#mask_boxes').click(function () {
        $(this).hide();
        $(box).hide();

        if (box == ".loginBox") {
            $('.loginBox').css('background', 'url(/Content/Design/ConnexionBox.png) no-repeat scroll 0 0 transparent');
            $('.register').show();
            $('.fbConnect').show();
            $("#logForm").show();
            $("#registerForm").hide();
        }
    });

    return false;
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////    START SEARCH          //////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


function searchByDate(order) {
    $('.photo').show();
    if (order == "invert")
        $.tinysort.defaults.order = $.tinysort.defaults.order == "desc" ? "asc" : "desc";
    else
        $.tinysort.defaults.order = order;

    $(".photo").tsort(".PublishedDate", { attr: "value" });

    pageIndex = 0;
    $('.navigation_left')[0].style.visibility = 'hidden';
    $('.box').css('marginTop', 0);
    showImages();
    if ($('.photo img:visible').length < 12)
        $('.navigation_right')[0].style.visibility = 'hidden';
    else
        $('.navigation_right')[0].style.visibility = 'visible';

    return false;
}

function searchByMark(order) {
    $('.photo').show();
    if (order == "invert")
        $.tinysort.defaults.order = $.tinysort.defaults.order == "desc" ? "asc" : "desc";
    else
        $.tinysort.defaults.order = order;
    $(".photo").tsort(".Mark", { attr: "value" });

    pageIndex = 0;
    $('.navigation_left')[0].style.visibility = 'hidden';
    $('.box').css('marginTop', 0);
    showImages();
    if ($('.photo img:visible').length < 12)
        $('.navigation_right')[0].style.visibility = 'hidden';
    else
        $('.navigation_right')[0].style.visibility = 'visible';

    return false;
}

function searchByRdm() {
    $('.photo').show();
    $(".photo").tsort("", { order: "rand" });

    pageIndex = 0;
    $('.navigation_left')[0].style.visibility = 'hidden';
    $('.box').css('marginTop', 0);
    showImages();
    if ($('.photo img:visible').length < 12)
        $('.navigation_right')[0].style.visibility = 'hidden';
    else
        $('.navigation_right')[0].style.visibility = 'visible';

    return false;
}

function searchByMyPictures() {
    $('.photo').hide();
    var identifiant = $('#identifiant').val();
    $('.photo').each(function (i) {
        if ($('.UserName', this).val() == identifiant) {
            $(this).prependTo('.albumViewer');
            $(this).show();
        }
    });

    pageIndex = 0;
    $('.navigation_left')[0].style.visibility = 'hidden';
    $('.box').css('marginTop', 0);
    showImages();
    if ($('.photo img:visible').length < 12)
        $('.navigation_right')[0].style.visibility = 'hidden';
    else
        $('.navigation_right')[0].style.visibility = 'visible';
    return false;
}

function searchByText() {
    if (validate_searchPicture() == false)
        return false;

    var SearchTxt = $('#searchTxt').val();

    $.post(
    '/Picture.aspx/Search/',
    { searchTxt: SearchTxt },
     function (result) {
         //TODO HERE 
         $('.photo').hide();
         var filter = result.split(';');
         var len = filter.length;
         for (var i = 0; i < len; i++) {
             var value = filter[i];
             $('#' + value).prependTo('.albumViewer');
             $('#' + value).show();
         }

         pageIndex = 0;
         $('.navigation_left')[0].style.visibility = 'hidden';
         $('.box').css('marginTop', 0);
         showImages();
         if ($('.photo img:visible').length < 12)
             $('.navigation_right')[0].style.visibility = 'hidden';
         else
             $('.navigation_right')[0].style.visibility = 'visible';
     });
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////    START MODAL           //////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

$(document).ready(function () {
    //select all the a tag with name equal to modal  
    $('a[name=modal]').click(function (e) {
        //Cancel the link behavior  
        e.preventDefault();
        //Get the A tag  
        var id = $(this).attr('href');

        //Get the screen height and width  
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();

        //Set height and width to mask to fill up the whole screen  
        $('#mask').css({ 'width': maskWidth, 'height': maskHeight });

        //transition effect       
        $('#mask').fadeIn(1000);
        $('#mask').fadeTo("slow", 0.8);

        //Get the window height and width  
        var winH = $(window).height();
        var winW = $(window).width();

        //Set the popup window to center  
        $(id).css('top', winH / 2 - $(id).height() / 2);
        $(id).css('left', winW / 2 - $(id).width() / 2);

        //transition effect  
        $(id).fadeIn(2000);

    });

    //if close button is clicked  
    $('.window .close').click(function (e) {
        //Cancel the link behavior  
        e.preventDefault();
        $('#mask, .window').hide();
    });

    //if mask is clicked  
    $('#mask').click(function () {
        $(this).hide();
        $('.window').hide();
    });

});

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////    IMAGE LOADER      ////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//$(document).ready(function () {
//    showImages();
//});

function showImages() {
    var startItem = (pageIndex * pageSize) - (pageCacheSize * pageSize);
    if (startItem < 0)
        startItem = 0;
    var endItem = (pageIndex * pageSize) + ((pageCacheSize + 1) * pageSize);

    $('div.photo').slice(startItem, endItem).find("img[src$='javascript:void(0)']").each(function () {
        var src = $(this).siblings('.imgSrc').val();
        $(this).attr('src', src);
    });
}
