﻿//Facebook pop up functions
var modalFacebook = null;
var modalErrors = null;
var FBContentLoadComplete=0;
var aid='';
var UploadedPictures=0;
MAXPHOTO = 8;
var btncontinue=document.getElementById('fbtext6').innerHTML;
var btncontinueselected=document.getElementById('fbtext7').innerHTML;

var FBShowContent=0;
function loadModalComplete() {
        document.getElementById('formUploadFBcontent').style.display = 'none';
        document.getElementById('albumContainer').style.display = 'block';
         if (UploadedPictures!=MAXPHOTO) {
              clearUploadFormFB();
              }
            if (aid != '') {
                document.getElementById("albumContainer").style.display = 'block';
                document.getElementById("picContainer_" + aid).style.display = 'none';
            }
            if (document.getElementById("bottomdivPic")) {
                document.getElementById("bottomdivPic").style.display = 'none';
            }            
    FBContentLoadComplete = 1;
}

function ShowModalUploadFacebook()
{
            if (null == modalFacebook) {
                // set up the modal
                modalFacebook = $('#popupFacebook').dialog({
                    autoOpen: false,
                    closeOnEscape: true,
                    draggable: false,
                    modal: true,
                    position: ['',155],
                    resizable: false,
                    dialogClass: 'modalExampleFB',
                    width: 725                               
                });
            }            
            //$('#popupFacebook').dialog('option', 'maxHeight', 100);
            document.getElementById('hdnUploadSelectedFB').value = 'fb';
            modalFacebook.dialog('open');
            document.getElementById('albumContainer').style.display = 'none';
            document.getElementById('formUploadFBcontent').style.display = 'block';
   // }
}
function showError(title,msg) {
    if (null == modalErrors) {
        // set up the modal
        modalErrors = $('#FBErrors').dialog({
            autoOpen: false,
            closeOnEscape: true,
            draggable: false,
            modal: true,
            position: 'center',
            resizable: false,
            dialogClass: 'modalExample',
            width: 642
        });
    }
    document.getElementById('ui-dialog-title-FBErrors').innerHTML = title;
    document.getElementById('errormessage').innerHTML = msg;
    //clearUploadFormFB();
    //document.getElementById('hdnUploadSelectedFB').value = 'fb';
    modalErrors.dialog('open');
    
    //uploadCompletedFB(result, msg);
}

function closeUploadFB() {
    //clear picture for upload
    selectedPictureForUpload = '';
    modalFacebook.dialog('close');
}   
	
	
	      var userFBFirstName='';
        var userFBLastName='';
	function clearUploadFormFB(){
	    document.getElementById('ui-dialog-title-popupFacebook').innerHTML = userFBFirstName + " "+ userFBLastName +"&nbsp;" + document.getElementById('fbtext1').innerHTML;	   
	    document.getElementById('formFBUpload').style.display = 'block';
	    document.getElementById('formUploadUploadingFB').style.display = 'none';
	}
	function uploadCompletedFB(result, msg){

	    if (result != 0) {
	        //console.log('sdasd');
	        //console.log("sss");
	        document.getElementById('modalLoadingAnimationFB').innerHTML = msg;
	        document.getElementById('formUploadingButtonsFB').style.display='block';
	        document.getElementById('formUploadUploadingFB').style.display='none';	        
	    }
	    else{
	        document.getElementById('formUploadUploadingFB').style.display='none';
	        closeUploadFB();
	        $.get('/_api/tattoodle-your-photos-api.aspx?a=getPhotosUp&zz=' + (new Date().getTime()), null, function(result){
	            topDraggables.draggable('destroy');
	            $('#imgCollectionImages').html(result);
	            SetTopDraggables();
	        }, 'html');
	        document.getElementById('hdnUploadSelectedFB').value="";
	    }
	}

    function backToUploadFB(){
	    clearUploadFormFB();
	    document.getElementById('formUploadUploadingFB').style.display = 'none';
	    document.getElementById('formFBUpload').style.display='block';
	    document.getElementById('formUploadingButtonsFB').style.display='none';
	    document.getElementById('modalLoadingAnimationFB').innerHTML = '<img src="/images/tattoodle-your-photos/Loading-Image-TattoodlePhoto.gif" />';
	    document.getElementById('hdnUploadSelectedFB').value="";
	}
    function setBoxBorderOn(obj)
    {
        document.getElementById("OutColorPlaceHolder_" + obj).className='OverColorPlaceHolder';
    }
    function setBoxBorderOff(obj)
    {
        document.getElementById("OutColorPlaceHolder_" + obj).className='OutColorPlaceHolder';
    }

    function FBUploadOnOver(obj)
    {
    document.getElementById("divFBpicture_" + obj).className='divFBpictureOnOver';
    }
    function FBUploadOnOut(obj)
    {
    document.getElementById("divFBpicture_" + obj).className='divFBpictureOnOut';
    }
    var lastchecked=-1;
    function FBUploadClick(obj,obj2)
    {                         
                document.getElementById("hdnUploadSelectedFB" ).value=obj2;
                lastchecked=obj;     
    }
   
var elementsSelected=''; 
var uploadremaining=0;
var clicuploadRemaining=0;
function showAlbumPictures(obj, obj2) {
    document.getElementById("modalUploadUploadFB").src = btncontinue;   
        uploadremaining = MAXPHOTO - UploadedPictures;
        clicuploadRemaining = uploadremaining;
        document.getElementById("TopText").innerHTML = document.getElementById("fbtext2").innerHTML + MAXPHOTO + document.getElementById("fbtext3").innerHTML + UploadedPictures + document.getElementById("fbtext4").innerHTML+'<span id="moreremaining" style="display:inline;">' + clicuploadRemaining + '</span>&nbsp;'+document.getElementById("fbtext5").innerHTML;

        document.getElementById("albumContainer").style.display = 'none';
        document.getElementById("picContainer_" + obj).style.display = 'block';
        document.getElementById("bottomdivPic").style.display = 'block';
        //document.getElementById("TopText").style.display='block';
        aid = obj;
        //"5893088398792935368","5893088398792933620",
        var picturesSelected = elementsSelected.split(',');
        // console.log( picturesSelected.length);
        for (i = 0; i < picturesSelected.length; i++) {
            if ('' === picturesSelected[i]) { continue; }
            document.getElementById("divPicSelFB_" + picturesSelected[i]).className = 'FBpictures';
            document.getElementById("imgFB_" + picturesSelected[i]).style.display = 'none';
            // console.log ( picturesSelected[i] );
        }
  //  }
}
function ShowAlbums()
{
document.getElementById("modalUploadUploadFB").src=btncontinue;
          //clear picture for upload
	        selectedPictureForUpload='';
	        //
    document.getElementById("albumContainer").style.display = 'block';
	    document.getElementById("picContainer_"+aid).style.display='none';
	    document.getElementById("bottomdivPic").style.display='none';
	    //document.getElementById("TopText").style.display='none';
	    
}

var selectedPictureForUpload='';
//var apicture='';
function selectPictureFB(obj2,obj3)
{
//console.log("enter " +selectedPictureForUpload);
  if (document.getElementById("imgFB_"+obj2).style.display=='none')
  { 
    if (clicuploadRemaining!=0)
    {
      clicuploadRemaining--;
      if (clicuploadRemaining==uploadremaining){
        document.getElementById("modalUploadUploadFB").src=btncontinue; 
      }
      else
      {
        document.getElementById("modalUploadUploadFB").src=btncontinueselected;
      }
      //document.getElementById("moreremaining").innerHTML=clicuploadRemaining;  
      document.getElementById("divPicSelFB_"+ obj2).className = 'FBpicturesContainerSelected';
      document.getElementById("imgFB_"+obj2).style.display='block';
      elementsSelected+=''+obj2+',';
      selectedPictureForUpload +=''+ obj3+',';   
      selectedPictureForUpload=selectedPictureForUpload;
      
    }
    else if (clicuploadRemaining==0 && UploadedPictures!= MAXPHOTO)
    {
        showError(errorFBmessage6, errorFBmessage2)
    }
    else if (UploadedPictures==MAXPHOTO)
    {
        showError(errorFBmessage6, errorFBmessage3)
    }
  }
  else
  {
    clicuploadRemaining++;
    if (clicuploadRemaining==uploadremaining){
        document.getElementById("modalUploadUploadFB").src=btncontinue; 
      }
      else
      {
        document.getElementById("modalUploadUploadFB").src=btncontinueselected;
      }
    //document.getElementById("moreremaining").innerHTML=clicuploadRemaining; 
    document.getElementById("divPicSelFB_"+ obj2).className = 'FBpictures';
    document.getElementById("imgFB_"+obj2).style.display='none';
   selectedPictureForUpload = selectedPictureForUpload.replace(obj3+',', "");
    //console.log("enter" + a);
  }
  //console.log("end "+selectedPictureForUpload);
  //console.log(elementsSelected);
}

function startUploadFB(){
    if (clicuploadRemaining==uploadremaining){ 
           showError(errorFBmessage6, errorFBmessage5)
     return false;
	    }
	    else
	    {	    
	     document.getElementById("hdnUploadSelectedFB" ).value=selectedPictureForUpload;    
	    //if ('' == document.getElementById('filePhoto').value){return false;}
	    //document.getElementById('ui-dialog-title-modalUpload').innerHTML = 'Loading Photo';
	    document.getElementById('formUploadingButtonsFB').style.display='none';
	      document.getElementById('modalLoadingAnimationFB').innerHTML = '<img src="/images/tattoodle-your-photos/Loading-Image-TattoodlePhoto.gif" />';
	    document.getElementById('formFBUpload').style.display = 'none';
	    document.getElementById('formUploadUploadingFB').style.display = 'block';
	    return true;
	    
	    }
	}

	var FacbookBTNClick = 0;
	var passGetUser = 0;
	var loadcomplete=0;
	var errorFBmessage1=document.getElementById("errorFBmessage1").innerHTML;
	var errorFBmessage2=document.getElementById("errorFBmessage2").innerHTML;
	var errorFBmessage3=document.getElementById("errorFBmessage3").innerHTML;
	var errorFBmessage4=document.getElementById("errorFBmessage4").innerHTML;
	var errorFBmessage5=document.getElementById("errorFBmessage5").innerHTML;
	var errorFBmessage6=document.getElementById("errorFBmessage6").innerHTML;
	//var firstHit = 0;

//Facebook functions end

//fb all conection functions



var finishLogin=0;
var isLogin=0;
var pagereload=0;

function connectFirstTimeuser()
{

if (userstate==2){
  if (finishLogin==1)
  {
  getFBUserAlbums();
  }else{
    isLogin=1; 
    FB.Connect.requireSession(theInitFunction);
  }
} else if (userstate==1){
if (pagereload==0){
pagereload=1;
postbackpage();
}else{
getFBUserAlbums();}
}


}
function postbackpage(){
 FB.Facebook.apiClient.users_getLoggedInUser(function(result, ex) {                                          
              userid = result;                        
              FB.Facebook.apiClient.users_getInfo(userid, 'last_name, first_name', function(getInfoFB, ex) {
                      userFBFirstName = getInfoFB[0].first_name;
                      userFBLastName = getInfoFB[0].last_name + '\'s';
                      finishLogin=1;
                        getFBUserAlbums();                               
          });
      }); 
}
function theInitFunction() {
   FB.Connect.forceSessionRefresh(function () {
   FB.Facebook.get_sessionState().waitUntilReady(function() { 
          FB.Facebook.apiClient.users_getLoggedInUser(function(result, ex) {                                          
              userid = result;                        
              FB.Facebook.apiClient.users_getInfo(userid, 'last_name, first_name', function(getInfoFB, ex) {
                      userFBFirstName = getInfoFB[0].first_name;
                      userFBLastName = getInfoFB[0].last_name + '\'s';
                      finishLogin=1;
                      pagereload=1;
                        getFBUserAlbums();                               
          });
      }); 
  });
  });                    
}
            
function getFBUserAlbums()
{
document.getElementById("albumContainer").innerHTML="";
document.getElementById("pictureContainer").innerHTML="";
var myCars = new Array();

var albumLenght = 0;
var pictureLenghtt = 0;
var pictureLenght = 0;
var indexAlbums = 0;
var noalbum = 0;
var lastaid = 0;
var str3 = '';
var str2 = '';
var str4 = '';
var str = '';
UploadedPictures = document.getElementById("hdnexistingPicture").value;
 FB.Facebook.apiClient.photos_getAlbums(null, null, function(getAlbums, ex) { 
 if (getAlbums==null){
     
      isLogin=1;  
      FB.Connect.requireSession(theInitFunction);                                     
      }else{
       if (UploadedPictures==MAXPHOTO) {showError(errorFBmessage6, errorFBmessage3)
       }else {ShowModalUploadFacebook();} 

      var index = 0;

      if (getAlbums.length == undefined) {
          if (FacbookBTNClick == 1) {
              closeUploadFB();
              showError('Tattoodle - Facebook Upload Error', errorFBmessage1)

          }
          noalbum = 1;
      }
      else {
          albumLenght = getAlbums.length;
          for (var i = 0; i < getAlbums.length; i++) {
              if (getAlbums[i].size == 0) {
                  str2 += '<div id="container_' + getAlbums[i].aid + '" class="albumContainer"  onclick="showError(\'Tattoodle - Facebook Upload Error\', errorFBmessage4)"';                                                
              }
              else {
                  str2 += '<div id="container_' + getAlbums[i].aid + '" class="albumContainer"  onclick="showAlbumPictures(\'' + getAlbums[i].aid + '\',' + pictureLenghtt + ')"';
              }
              str2 += '>';
              str2 += '<div id="album_' + getAlbums[i].aid + '" class="albumDiv" ></div>';
              str2 += '<div style="margin:0px;color:#2669E5;text-decoration:underline;width:154px;text-align:center;">' + getAlbums[i].name + '</div>';
              str2 += '</div>';
              document.getElementById('albumContainer').innerHTML = str2;                                            
              FB.Facebook.apiClient.photos_get(null, getAlbums[i].aid, null, function(getPhotos, ex) {
                  loadcomplete = 1;
                  indexAlbums++;
                  pictureLenght++;                                                
                  if (getPhotos.length == undefined) {                                                    
                  } else {
                      for (var j = 0; j < getPhotos.length; j++) {
                          if (getPhotos[j].aid != lastaid) {
                              document.getElementById('album_' + getPhotos[j].aid).innerHTML = '<div id="albumPicture_' + getPhotos[j].aid + '" style="width:148px;height:148px;background-position:center center;background-repeat:no-repeat;margin:0px;text-align:center;background-image:url(' + getPhotos[j].src_small + ')"></div>';
                              str3 += '<div  id="picContainer_' + getPhotos[j].aid + '" style="display:none;">';
                          }
                          str3 += '<div id="divPicFB_' + getPhotos[j].pid + '" class="FBpicturesContainer">';
                          str3 += '<div id="divPicSelFB_' + getPhotos[j].pid + '" class="FBpictures" onclick="selectPictureFB(\'' + getPhotos[j].pid + '\',\'' + getPhotos[j].src_big + '\')" style="background-image:url(' + getPhotos[j].src + ')"></div>';
                          str3 += '<img id="imgFB_' + getPhotos[j].pid + '" style="display:none;" class="FBpicturesImg" src="/images/tattoodle-your-photos/fbselected.gif"/>';
                          str3 += '</div>';
                          lastaid = getPhotos[j].aid;
                      }
                      str3 += '</div>';
                  }
                  if (indexAlbums == albumLenght) 
                  {                     
                      str4 += '<div id="bottomdivPic" style="display:none;">';
                      str4 += '<div id="TopText" ></div>';
                      str4 += '<div id="picturesubcontainer">' + str3 + '</div>';  
                      str4 += '<div id="GoBack" style="font-weight:bold;font-size:11px;cursor:pointer;color:#2669E5;padding-left:20px;text-decoration:underline; position:relative; width:476px; top:34px;" onclick="ShowAlbums();">'+document.getElementById("imgAlbumGoBack").value+'</div>';                    
                      str4 += '<div style="color: rgb(127, 127, 127); font-size: 11px; line-height: 11px; padding-left:20px; position:relative; width:476px; top:38px;">' +document.getElementById("fbdisclaimlit").value + '</div>';                      
                      str4 += '<input id="modalUploadUploadFB" style="margin-right:40px;" type="image" onclick="return startUploadFB();" value="Upload" src="/images/tattoodle-your-photos/FBcontinuebtn.gif"/>';
                      str4 += '</div>';
                      document.getElementById('pictureContainer').innerHTML = str4;
                      indexAlbums = 0;
                      pictureLenghtt = 0;
                      pictureLenght = 0;
                          loadModalComplete();
                          loadcomplete = 1;                 
                  }
            });
          }
        }
      }
    });
}