var mySwiper;
var sliderArray;
var currId;
var swiperOn = 0;
var activeBlock=1;
var curSliderHeight = 0;

function closeSwiper(){
    swiperOn = 0;
    document.getElementById('swiperPMHolder').innerHTML='';
    document.getElementById('swiperPMHolderFS').innerHTML='';
    document.getElementById('swiperPMHolder').style.display='none';
    document.getElementById('swiperPMHolderFS').style.display='none';
    activeBlock=0;
    mySwiper.destroy(true,true);

    if (mobileUpload) {unbindRebuild();}
}

function unbindRebuild() {
    $('#swiperPMHolder').off('touchmove');
    $('#swiperPMHolderFS').off('touchmove');
}
function rebuildOnScroll() {
    unbindRebuild();

    if (document.getElementById('fScreenNavControl').className=='mobileFullscreenNavControl') {
        $('#swiperPMHolder').bind('touchmove', function(e) {
            rebuildSwiper();
        });
    } else {
        $('#swiperPMHolderFS').bind('touchmove', function(e) {
            rebuildSwiper();
        });        
    }
}
var rebuildTimer;
function rebuildSwiper() {
    clearTimeout(rebuildTimer);
    rebuildTimer = setTimeout(function() {
        var updateRand = getRandomArbitrary(0, 5);
        // mySwiper.updateAutoHeight(100);
        $('.swiper-slide-active').css('height', curSliderHeight+updateRand);
        // mySwiper.slideReset(500, false);
    }, .2*1000);
   
}
function getRandomArbitrary(min, max) {
    return Math.random() * (max - min) + min;
}
function buildSwiper(pmId){
    swiperOn = 1;
    activeBlock=1;
    $.ajax({
        url: "swiperPopup.php",
        type: "POST",
        data: {
            x: indexX,
            y: indexY,
            pmid: pmId,
            action: 7
        },
        dataType: "html",
        success: function(data) {
            sliderArray = JSON.parse(data);
            buildSwiperStage2();
        }
    });
}

function buildSwiperStage2(){
    if($(window).width()<=767){
        newPhotoSwiper='<div class="swiper-container"><div class="swiper-wrapper"></div><div class="swiper-button-next swiper-button-white"></div><div class="swiper-button-prev swiper-button-white"></div>';
    } else {
        newPhotoSwiper='<div class="swiper-container"><div class="swiper-wrapper"></div><div class="swiper-button-next swiper-button-white" style="margin-right:'+(($(window).width()/2)-358)+'px;"></div><div class="swiper-button-prev swiper-button-white" style="margin-left:'+(($(window).width()/2)-358)+'px;"></div>';
    }
    if (document.getElementById('fScreenNavControl').className=='' || document.getElementById('fScreenNavControl').className=='mobileFullscreenNavControl') {
        document.getElementById('swiperPMHolder').style.display='inherit';
        document.getElementById('swiperPMHolder').innerHTML=newPhotoSwiper;
    } else {
        document.getElementById('swiperPMHolderFS').style.display='inherit';
        document.getElementById('swiperPMHolderFS').innerHTML=newPhotoSwiper;
    }
    if (mobileUpload) {rebuildOnScroll();}

    mySwiper = new Swiper ('.swiper-container', {
        loop: false,
        loopAdditionalSlides: 0,
        loopedSlides: null,
        slidesPerView:1,
        nextButton: '.swiper-button-next',
        prevButton: '.swiper-button-prev',
        autoHeight: true
    });

    mySwiper.on('onSlidePrevStart', function () {
        popupPhotoSwipe(-1);
    });
    mySwiper.on('onSlideNextStart', function () {
        popupPhotoSwipe(1);
    });

    for(var i = 0; i<sliderArray.length;i++){
        if(parseInt(sliderArray[i].xCoord) == indexX && parseInt(sliderArray[i].yCoord) == indexY){
            if((indexX == (userImgX+1)) && (indexY == (userImgY+1))) {
                var url = 'upload_flat_complete/thumbnail3/'+animImage+'.jpg';
            } else {
                var url = 'upload_flat_complete/thumbnail3/'+sliderArray[i].code+'.jpg';
            }
            var imgClicked = new Image();
            imgClicked.onload = (function(num) {
                return function(){
                    currId = parseInt(sliderArray[num].pm_id);
                    imgLoadedInitial(this, num);
                }
            })(i);
            imgClicked.src = url;
            break;
        }
    }
}

function imgLoadedInitial(loadedImg, loopPos){
    if(activeBlock){
        sliderArray[loopPos].width = loadedImg.width;
        sliderArray[loopPos].height = loadedImg.height;
        var theDiv = buildDiv(loadedImg.src, sliderArray[loopPos]);
        mySwiper.prependSlide(theDiv);
        curSliderHeight = mySwiper.slides[mySwiper.activeIndex].offsetHeight;
        loadSurrounding(loopPos-1, -1);
        loadSurrounding(loopPos+1, 1);
    }
}

function imgLoaded(loadedImg, loopPos, position){
    if(activeBlock){
        sliderArray[loopPos].width = loadedImg.width;
        sliderArray[loopPos].height = loadedImg.height;
        var theDiv = buildDiv(loadedImg.src, sliderArray[loopPos]);
        if(position >= 0){
            mySwiper.appendSlide(theDiv);
        }else{
            mySwiper.prependSlide(theDiv);
        }
    }
}
function buildDiv(src, data){
    var name, caption;
    if(data.lname != '') {
        name = data.fname+' '+data.lname.substring(0,1) +'.';
    } else {
        name = data.fname;
    }
    caption = decodeHtml(data.caption);

    var localShare = getShares(data.code);
    var likeButton = '';
    
    var favorited = checkUserFavorite(data.code);
    console.log("here 1: " + data.code);
    console.log("favorited: " + favorited);
    if (favorited >= 0){
        // likeButton = '<div class="unfavorite" onClick="unfavoritePhoto(\''+data.code+'\', '+localShare+', 0); return false; "><span class="likeHeart">&#10084;</span></div>';
        likeButton = '<div class="unfavorite" onClick="unfavoritePhoto(\''+data.code+'\', '+localShare+', 0); return false; "><img src="images/heart_solid_red.svg" class="likeHeart"/></div>';
    } else {
        likeButton = '<div class="favorite" onClick="favoritePhoto(\''+data.code+'\', '+localShare+', 0); return false; "><img src="images/heart_outline_red.svg" class="likeHeart"/></div>';
    }

    //var fbLikeBtn = '<div class="fb-like" data-href="https://'+GLOBAL_DOMAIN+'/mosaic.php?key='+photoCode+'&src=fb" data-layout="button_count" data-action="like" data-size="small" data-width="85px" data-show-faces="true" data-share="false"></div>';

    var newPhotoSwiper='<div class="swiper-slide"><div id="infoHolderSwiper-'+data.code+'" class="infoHolderSwiper">'; // two </div> expected

        newPhotoSwiper += '<div class="swiperImgHolder">'; // one </div> expected

        newPhotoSwiper += '<div class="swiperImg"><img src="'+src+'" /></div>';

        newPhotoSwiper += '</div>'; // close swiperImgHolder

        newPhotoSwiper += '<div class="swiperInfo">'; // one </div> expected
        if(!((data['xCoord'] == (userImgX+1)) && (data['yCoord'] == (userImgY+1)))) {
            newPhotoSwiper += '<div class="swiperData">'; // one </div> expected
            
            newPhotoSwiper += '<div class="swiperUser"><div class="swiperName">'+name+'</div><div class="photoFunction"><div class="photoLikeBtn '+data.code+' click noselect" >'+likeButton+'</div><div class="likeAmount"><span class="likeCounter-'+data.code+'">'+localShare+'</span></div></div>'; // one </div> expected

            //newPhotoSwiper += fbLikeBtn;

            newPhotoSwiper += '</div>'; // close swiperUser

            newPhotoSwiper += '<div class="swiperCap">'+caption+'</div>';

            newPhotoSwiper += '</div>'; // close swiperData

            newPhotoSwiper += '<div class="swiperBtm">';  // one </div> expected

            newPhotoSwiper += '<div class="swiperShare"><div class="swiperShareTxt">'+SHARE_PHOTO+'</div><div class="swiperShareIcons">';
            newPhotoSwiper += '<div class="click swipeShareFB" onclick="fbPhotoShare(\''+data.code+'\');"></div>';
            newPhotoSwiper += '<div class="click swipeShareTW" onclick="twPhotoShare(\''+data.code+'\');"></div>';
            //newPhotoSwiper += '<div class="click swipeShareIN" onclick="inPhotoShare(\''+data.code+'\');"></div>';
            newPhotoSwiper += '<div class="click swipeShareEmb" onclick="toggleEmbed(); return false;" ></div>';
            newPhotoSwiper += '</div></div>';

            newPhotoSwiper += '</div>'; // close swiperBtm

            newPhotoSwiper += '</div>'; // close swiperInfo
        } else {
            newPhotoSwiper += '<div class="swiperData">'; // one </div> expected
            newPhotoSwiper += '<div class="swiperCap">'+INSTA_ADD_INFO+'</div>';
            newPhotoSwiper += '</div>'; // close swiperData
            $('.swiper-button-white').hide();
        }
        newPhotoSwiper += '<div class="swiper-close" onclick="closeSwiper(); event.preventDefault();" ontouchend="closeSwiper(); event.preventDefault();"></div>';

        newPhotoSwiper += '</div></div>'; // close infoHolderSwiper and swiper-slide


  return newPhotoSwiper;
}
function decodeHtml(html) {
    var txt = document.createElement("textarea");
    txt.innerHTML = html;
    return txt.value;
}

function loadSurrounding(startPos, direction){
    var url = 'upload_flat_complete/thumbnail3/'+sliderArray[startPos].code+'.jpg';
    var img = new Image();
    img.onload = (function(imgData) {
        return function(){
            imgLoaded(this, imgData[0], imgData[1]);
            var val = imgData[0]+imgData[1];
            if( val >= 0 && val < sliderArray.length ){
                loadSurrounding(val, imgData[1]);
            }
        }
    })([startPos, direction])
    img.src = url;
}
function newSwiperImage(data, direction){
    var newImg = new Image();
    newImg.onload = (function() {
        var swiperVal = direction == -1 ? 0 : sliderArray.length - 1;
        sliderArray.length-1
        sliderArray[swiperVal].width = this.width;
        sliderArray[swiperVal].height = this.height;
        var newSwiperImg = buildDiv(this.src, data);

        if(direction == -1){
            mySwiper.prependSlide(newSwiperImg);
            mySwiper.removeSlide(7);
        } else{
            mySwiper.appendSlide(newSwiperImg);
            mySwiper.removeSlide(0);
        }
    });
    newImg.src = 'upload_flat_complete/thumbnail3/'+data.code+'.jpg';
}

function popupPhotoSwipe(direction){
    curSliderHeight = mySwiper.slides[mySwiper.activeIndex].offsetHeight;
    //mySwiper.lockSwipes();
    var id = currId + (4 * direction);
    currId = currId + direction;
    //photo that was swiped too
    var currIndex = sliderArray.map(function(d){return d['pm_id'];}).indexOf(currId.toString());
    moveBox(sliderArray[currIndex].xCoord, sliderArray[currIndex].yCoord);
    //recordOutboundLink('','Mosaic Photo Clicks', sliderArray[currIndex].code );
    var dataExists = false;
    
    var dataIndex;
    for(dataIndex = 0 ; dataIndex < sliderArray.length ; dataIndex++){
        if( parseInt(id) == parseInt(sliderArray[dataIndex].pm_id )) {
            dataExists = true;
            break;
        }
    }

    if(!dataExists){
        $.ajax({
            url: "swiperPopup.php",
            type: "POST",
            data: {
                action: direction, //can be -1 (left) or 1 (right)
                pmid: id
            },
            dataType: "html",
            success: function(data) {
                var data = JSON.parse(data);
                newSwiperImage(data[0], direction);
                if(direction == -1){
                    sliderArray.unshift(data[0]);
                }else{
                    sliderArray.push(data[0]);
                }
                }
        });
    }else{
        newSwiperImage(sliderArray[dataIndex], direction);
    }
}

function moveBox(x,y){
    goToHotspot(x,y);
}


// like logic

function checkUserFavorite(code) {
	var found = favoriteArray.indexOf(code);
	return found;
}

function getFavorites() {
    var favorites = $.jStorage.get('user', 0);
    console.log("favorties: " + favorites);
    if(favorites) {
        favoriteArray = favorites.split(",");
    } else {
        favoriteArray = [];
    }
}

function getShares(code) {
    var localShare = 0;
    $.ajax({
        type: "GET",
        url: "getShares.php",
        data: {
            code: code
        },
        dataType: "html",
        async: false,
        success: function(data) {
            var temp = JSON.parse(data);
            temp = temp[0];
            localShare = temp == undefined ? 0 : temp['total'];
            console.log("local share: " + localShare);
        }
    });
    return localShare;
}

function unfavoritePhoto(code, passedShare, info) {
    getFavorites();
    var favorited = checkUserFavorite(code);
    passedShare--;
    console.log(favorited);
    if(favorited >= 0) {
        $.ajax({
            url: "unfavoritePhoto.php",
            type: "POST",
            data: {
                code : code,
                email : emailGet
            },
            dataType: "html",
            success: function(data) {
                if(info) {
                    console.log("here 1");
                    $('.'+code+'-info').html('<div class="favorite" onClick="favoritePhoto(\''+code+'\', '+passedShare+', 1); return false;"><img src="images/heart_outline_red.svg" class="likeHeart"/></div>'); //added -- IAN
                } else {
                    console.log("here 2");
                    $('.'+code).html('<div class="favorite" onClick="favoritePhoto(\''+code+'\', '+passedShare+', 0); return false;"><img src="images/heart_outline_red.svg" class="likeHeart"/></div>'); //added -- IAN
                    $('.'+code+'-info').html('<div class="favorite" onClick="favoritePhoto(\''+code+'\', '+passedShare+', 1); return false;"><img src="images/heart_outline_red.svg" class="likeHeart"/></div>');
                }
                updateSharesDec(code, passedShare);
                var place = favoriteArray.indexOf(code);
                favoriteArray.splice(place, 1);
                overwriteJstorage();
            }
        });
    } else {
        recordOutboundLink(this, 'Mosaic Caught Un-Like Cheating', code);
        console.log("cheating");
    }
}

function favoritePhoto(code, passedShare, info) {
    getFavorites();
    var favorited = checkUserFavorite(code);
    passedShare++;
    if(favorited < 0) {
        $.ajax({
            url: "favoritePhoto.php",
            type: "POST",
            data: {
                code : code,
                email : emailGet
            },
            dataType: "html",
            success: function(data) {
                if(info) {
                    console.log("here 3");
                    $('.'+code+'-info').html('<div class="unfavorite" onClick="unfavoritePhoto(\''+code+'\', '+passedShare+', 1); return false;"><img src="images/heart_solid_red.svg" class="likeHeart"/></div>'); //added -- IAN
                } else {
                    console.log("here 4");	
                    $('.'+code).html('<div class="unfavorite" onClick="unfavoritePhoto(\''+code+'\', '+passedShare+', 0); return false;"><img src="images/heart_solid_red.svg" class="likeHeart"/></div>'); //added -- IAN
                    $('.'+code+'-info').html('<div class="unfavorite" onClick="unfavoritePhoto(\''+code+'\', '+passedShare+', 1); return false;"><img src="images/heart_solid_red.svg" class="likeHeart"/></div>'); //added -- IAN
                }
                updateSharesInc(code, passedShare);
                favoriteArray.push(code);
                overwriteJstorage();
            }
        });
    } else {
        recordOutboundLink(this,'Mosaic Caught Like Cheating', code);
        console.log("cheating fave");
    }
    console.log("fav p click");
    return false;
}

function overwriteJstorage() {
	var favoriteString = favoriteArray.join();
	$.jStorage.set('user', favoriteString, {TTL: 84600000});
}

function updateSharesInc(code, shareVal) {
    $('.likeCounter-'+code).html(shareVal);

}
function updateSharesDec(code, shareVal) {
    $('.likeCounter-'+code).html(shareVal);
}