/// <reference path="common.js" />

/*====Variable====*/
var slideshowImgFrom = 0;
var slideshowImgTo = 4;
var slideshowImageCollection = [];
var slideshowClickFlg = false;
var slideshowInitFlg = true;
var slideshowSelectedIndex = 0;
//0: next - 1: prev
var slideshowControlToggleFlg = 0;
var totalRecord;
var slideshowSelectFirstIndex = 0;
var slideshowSelectLastIndex = 4;
var slideshowMainCurrIndex = 0;
/*==========================================*/
function refreshSlideShowValue(){
    slideshowImgFrom = 0;
    slideshowImgTo = 4;
    slideshowImageCollection = [];
    slideshowClickFlg = false;
    slideshowInitFlg = true;
    slideshowSelectedIndex = 0;
    //0: next - 1: prev
    slideshowControlToggleFlg = 0;
    totalRecord;
    slideshowSelectFirstIndex = 0;
    slideshowSelectLastIndex = 4;
    slideshowMainCurrIndex = 0;
};


//Show Image Preview
function showImagePreview(targetId, imgList) {
    refreshSlideShowValue();
    //Check if imageList is not null
    if (imgList != null && imgList != 'undefined' && imgList.length > 0) {
        slideshowImageCollection = setImageSource(imgList);
        //Check if targetId is not null
        if (targetId != null && targetId != 'undefined') {
            if (slideshowImageCollection.length == 1) {
                targetId.html('');
                targetId.append('<div id="slideWrapper">'
                + '</div>');

                var mainImg = $('#slideWrapper');
                //START FIXCSS

                var cssObj = { 'background-image': 'url(' + slideshowImageCollection[0].thumbnail + ')',
                    'background-repeat': 'no-repeat',
                    'background-size': 'contain',
                    'background-position': 'center'
                };
                mainImg.addClass('imagePreview-one');
                //END FIXCSS


                mainImg.css(cssObj);

                mainImg.parent().css('padding-top', '0px');

            } else {
                renderSlideShowBackground(targetId);
                renderSelectImage();
                renderMainImage(0);
                handleImagePreviewEvent();
            }
        }
    }
    else {
        renderSlideShowBackground(targetId);
        $('.main-control').css('visibility', 'hidden');
        $('.slideshow-control').css('visibility', 'hidden');
    }
    optimizeSizeImagePreview();
};

//Set image source for slide show
function setImageSource(source){
    var oldSource = source;
    var newSource = [];
    
    for(var nIndex = 0; nIndex < oldSource.length; nIndex++){
        newSource.push({index : nIndex, image : oldSource[nIndex], thumbnail : oldSource[nIndex]});
    }
    
    return newSource;
};

//render background to show image preview
function renderSlideShowBackground(targetId){
    var targetDiv = targetId;
    targetDiv.html('');
    targetDiv.append('<div id="slideWrapper">'
    +'  <div class="gallery-image" id="gallery-image">'
    +'      <div class="main-control" id="main-control-prev"> </div>'
    +'      <div id="main-img" id="mainThumbnail"><div class="mainThumbnail"></div></div>'
    +'      <div class="main-control" id="main-control-next"> </div>'
    +'  </div>'
    +'  <div class="gallery-thumb">'
    +'      <div id="control-prev" class="slideshow-control"><img src="././img/arrow-left.gif"></div>'
    +'      <div id="selector-img">'
    +'      </div>'
    +'      <div id="control-next" class="slideshow-control"><img src="././img/arrow-right.gif"></div>'
    +'  </div>'
    +'</div>'   
    );

    $(window).resize(function () {

        optimizeSizeImagePreview();
    });

    //handleImagePreviewEvent();
};
function optimizeSizeImagePreview() {
    var maxW = "798";
    var ratio = 1.566;
    var maxH = maxW / ratio;



    if ($("#dialog").width() < maxW || $("#dialog").height() < maxH) {
        
        if ($("#dialog").width() < maxW) {
            $("#dialog").css('width', maxW + 'px');
            $("#dialog").css('height', maxH + 'px');
        }
        if ($("#dialog").height() < maxH) {
            $("#dialog").css('height', maxH + 'px');
            $("#dialog").css('width', maxW + 'px');
        }
    }
    else {
        $("#dialog").css('width', maxW + 'px');
        $("#dialog").css('height', maxH + 'px');
    }
    $("#dialog").center();
};

//render select image
function renderSelectImage(){
    var selectImg = $('#selector-img');
    
    $.each(slideshowImageCollection, function(i, image){
        if(slideshowImgFrom <= i && i <= slideshowImgTo){
            selectImg.append('<div class="thumbnail" imageId="'+ image.index +'" style="display:block; background-image : url('+image.thumbnail+')"></div>');
        }
        else{
            selectImg.append('<div class="thumbnail" imageId="'+ image.index +'" style="display:none; background-image : url('+image.thumbnail+')"></div>');
        }
    });
};

//Handle Image Preview Event
function handleImagePreviewEvent(){
    
    $('#control-next').click(imageSelectNextFunction);
    
    $('#control-prev').click(imageSelectPrevFunction);
    
    $('#main-control-next').click(imageMainSelectNextFunction);

    $('#main-control-prev').click(imageMainSelectPrevFunction);
    
    $('.thumbnail').click(selectImgClickFunction);
    
    $('.thumbnail').mouseenter(selectImgMouseEnterFunction);
    
    $('.thumbnail').mouseleave(selectImgMouseLeaveFunction);
    
    $('.main-control').css('opacity','0');
    
    
    $('#main-control-next').mouseleave(mainControlNextMouseLeaveFunction);
    
    
    $('#main-control-prev').mouseleave(mainControlPrevMouseLeaveFunction);
    
    if (COMMON.isTouchDevice() == false) {
        //$('.main-control').mouseenter(mainControlMouseEnterFunction);
        $('#main-control-next').mouseenter(mainControlNextMouseEnterFunction);
        $('#main-control-prev').mouseenter(mainControlPrevMouseEnterFunction);
    }
    
    //$('.main-control').mouseleave(mainControlMouseLeaveFunction);
    
    //$('.thumbnail:first').css('box-shadow','0px 7px 7px #555');
    $('.thumbnail:first').addClass('activeThumb');
    handleDispNextPrevButton();
};

function mainControlNextMouseEnterFunction(){
    $(this).css('opacity','0.5');
};

function mainControlNextMouseLeaveFunction(){
    $(this).css('opacity','0');
};

function mainControlPrevMouseEnterFunction(){
    $(this).css('opacity','0.5');
};

function mainControlPrevMouseLeaveFunction(){
    $(this).css('opacity','0');
};

//Image Preview next icon function
function imageSelectNextFunction(){

    if(slideshowSelectLastIndex < slideshowImageCollection.length - 1){
        $('#selector-img div:eq('+slideshowSelectFirstIndex+')').animate({width: 'hide'},
            {step: function(now, fx){                                       
                        $('#selector-img div:eq('+slideshowSelectLastIndex+')').animate({width: 'show'});                       
                }
            }
        );
        
        slideshowSelectFirstIndex = slideshowSelectFirstIndex + 1;
        slideshowSelectLastIndex = slideshowSelectLastIndex + 1;
        handleDispNextPrevButton();
    }
};

//Image preview prev icon function
function imageSelectPrevFunction(){
    var fixedIndex = slideshowSelectFirstIndex - 1;
    
    if(slideshowSelectFirstIndex > 0){
        
        $('#selector-img div:eq('+fixedIndex+')').animate({width: 'show'});
        $('#selector-img div:eq('+slideshowSelectLastIndex+')').animate({width:'hide'});
        slideshowSelectFirstIndex = slideshowSelectFirstIndex - 1;
        slideshowSelectLastIndex = slideshowSelectLastIndex - 1;
        handleDispNextPrevButton();
    }

};
var slideshow_isTransaction = false;

//Main Image next icon function
function imageMainSelectNextFunction() {

    if (COMMON.isTouchDevice() == true) {
        $('#main-control-next').css('opacity', '0.5');
    }


    if (slideshow_isTransaction == false) {
        slideshow_isTransaction = true;
        var fixedIndex = eval(slideshowMainCurrIndex) + 1;

        if (slideshowMainCurrIndex < slideshowImageCollection.length - 1) {
            $('#main-img div').animate(
            { "left": "-=100%" },
            {
                /*duration: "slow",*/
                complete: function () {
                    $('#main-img div').hide();
                    renderMainImage(fixedIndex);
                    $('#main-img div').css('left', '+=300%');
                    $('#main-img div').show();
                    $('<img/>').attr('src', slideshowImageCollection[fixedIndex].thumbnail).load(function () {
                        $('#main-img div').animate({ left: '0%' });
                    });
                    slideshowMainCurrIndex = eval(slideshowMainCurrIndex) + 1;
                    syncImageMainWithSelectImage();
                    handleDispNextPrevButton();
                }
            }
        );
        }
    }
};

//Main Image prev icon function
function imageMainSelectPrevFunction() {
    if (COMMON.isTouchDevice() == true) {
        $('#main-control-prev').css('opacity', '0.5');
    }

    if (slideshow_isTransaction == false) {
        slideshow_isTransaction = true;
        var fixedIndex = eval(slideshowMainCurrIndex) - 1;

        if (slideshowMainCurrIndex > 0) {
            $('#main-img div').animate(
            { "left": "+=100%" },
            {
                duration: "medium",
                complete: function () {
                    $('#main-img div').hide();
                    renderMainImage(fixedIndex);
                    $('#main-img div').css('left', '-=300%');
                    $('#main-img div').show();
                    $('<img/>').attr('src', slideshowImageCollection[fixedIndex].thumbnail).load(function () {
                        $('#main-img div').animate({ left: '0%' });
                    });
                    slideshowMainCurrIndex = eval(slideshowMainCurrIndex) - 1;
                    syncImageMainWithSelectImage();
                    handleDispNextPrevButton();
                }
            }
        );

        }
    }
};

//Selector Image click function
function selectImgClickFunction() {
    if (slideshow_isTransaction == false) {
        slideshow_isTransaction = true;
        var imgIndex = $(this).attr('imageId');

        if (imgIndex > slideshowMainCurrIndex) {
            $('#main-img div').animate(
            { "left": "-=100%" },
            {
                duration: "medium",
                complete: function () {
                    $('#main-img div').css('display', 'none');
                    renderMainImage(imgIndex);
                    $('#main-img div').css('left', '+=300%');
                    $('#main-img div').css('display', 'block');
                    $('<img/>').attr('src', slideshowImageCollection[imgIndex].thumbnail).load(function () {
                        $('#main-img div').animate({ left: '0%' });
                    });

                    slideshowMainCurrIndex = imgIndex;
                    handleDispNextPrevButton();
                }
            }
        );
        }
        else if (imgIndex < slideshowMainCurrIndex) {
            $('#main-img div').animate(
            { "left": "+=100%" },
            {
                duration: "medium",
                complete: function () {
                    $('#main-img div').css('display', 'none');
                    renderMainImage(imgIndex);
                    $('#main-img div').css('left', '-=300%');
                    $('#main-img div').css('display', 'block');
                    $('<img/>').attr('src', slideshowImageCollection[imgIndex].thumbnail).load(function () {
                        $('#main-img div').animate({ left: '0%' });
                    });
                    slideshowMainCurrIndex = imgIndex;
                    handleDispNextPrevButton();
                }
            }
        );
        }
        else {
            slideshow_isTransaction = false;
            slideshowMainCurrIndex = imgIndex;
            handleDispNextPrevButton();
        }

        //$('.thumbnail').css('box-shadow', '');
        $('.thumbnail').removeClass('activeThumb');
        //$(this).css('box-shadow', '0px 7px 7px #555');
        $(this).addClass('activeThumb');
        slideshowClickFlg = true;
    }
};

//Render Main Image
function renderMainImage(i) {
    
    var mainImg = $('#main-img div');
    mainImg.css('background-image', 'url(' + slideshowImageCollection[i].thumbnail + ')');

    slideshow_isTransaction = false;
    if (COMMON.isTouchDevice() == true) {
        $('#main-control-next').css('opacity', '0');
        $('#main-control-prev').css('opacity', '0');
    }
};

function selectImgMouseLeaveFunction(){
    if(!slideshowClickFlg){
        //$('this').css('box-shadow','');
        $('this').removeClass('activeThumb');
        slideshowClickFlg = false;
    }
    else{
        //slideshowClickFlg = false;
    }
};

function selectImgMouseEnterFunction(){
    
    //$('.thumbnail').css('box-shadow','');
    $('.thumbnail').removeClass('activeThumb');
    //$(this).css('box-shadow','0px 7px 7px #555');
    $(this).addClass('activeThumb');
};

//Main control mouse leave function
function mainControlMouseLeaveFunction(){   
    $('.main-control').css('opacity','0');
};

//Main control mouse enter function
function mainControlMouseEnterFunction(){
    $('.main-control').css('opacity','0.5');
};

//Sync Main Image with select Image
function syncImageMainWithSelectImage(){
    var thumbImg = $('.thumbnail[imageId="'+ slideshowMainCurrIndex +'"]'); 

    if(thumbImg.is(':hidden')){
        if(slideshowMainCurrIndex > slideshowSelectLastIndex){
            imageSelectNextFunction();
        }
        else if(slideshowMainCurrIndex < slideshowSelectFirstIndex){
            imageSelectPrevFunction();
        }
    }
    
    //$('.thumbnail').css('box-shadow','');
    $('.thumbnail').removeClass('activeThumb');
    //thumbImg.css('box-shadow','0px 7px 7px #555');
    thumbImg.addClass('activeThumb');
};

//Handle display button control
function handleDispNextPrevButton(){
    
    if(slideshowSelectFirstIndex > 0){      
        $('#control-prev').css('visibility','visible');
    }
    else{
        $('#control-prev').css('visibility','hidden');
    }
    
    if(slideshowSelectLastIndex < (eval(slideshowImageCollection.length) - 1)){ 
        $('#control-next').css('visibility','visible');
    }
    else{
        $('#control-next').css('visibility','hidden');
    }
    
    if(slideshowMainCurrIndex > 0){     
        $('#main-control-prev').css('visibility','visible');
    }
    else{
        $('#main-control-prev').css('visibility','hidden');
    }
    
    if(slideshowMainCurrIndex < (eval(slideshowImageCollection.length) - 1)){
        $('#main-control-next').css('visibility','visible');
    }
    else{
        $('#main-control-next').css('visibility','hidden');
    }
};