﻿google.load('search', '1');

var imageSearch;
var mycarousel_itemList = []
var autoMode = true;

function searchComplete() {
  // Check that we got results
  mycarousel_itemList = [];

  $('#photoHelper').show();

  if (imageSearch.results && imageSearch.results.length > 0) {
    var results = imageSearch.results;
    for (var i = 0; i < results.length; i++) {
      var result = results[i];
      mycarousel_itemList.push({url:result.url,title:result.titleNoFormatting,thumb:result.tbUrl})
    }

    loadCarousel(imageSearch.results.length);
  }
  else{
    $('#automaticPhotoSection').hide();
    $('#photoSelectionModeSwitch').hide();
    $('#manualPhotoSection').show();
    autoMode = false;
  }
}

function onLoad() {
  imageSearch = new google.search.ImageSearch();

  //imageSearch.setRestriction(google.search.ImageSearch.RESTRICT_IMAGESIZE,
                             //google.search.ImageSearch.IMAGESIZE_MEDIUM);
  imageSearch.setRestriction(google.search.ImageSearch.RESTRICT_IMAGETYPE,
                             google.search.ImageSearch.IMAGETYPE_FACES);

  imageSearch.setResultSetSize(google.search.Search.LARGE_RESULTSET);

  imageSearch.setSearchCompleteCallback(this, searchComplete, null);

  var q = '\"' + subjectDetails.fullName + '\" ' + subjectDetails.city + ' ' + subjectDetails.state; // + ' ' + subjectDetails.country;

  /*
  for(var r in subjectDetails.roles)
    q += ' ' + subjectDetails.roles[r];
  */

  imageSearch.execute(q);

    $('#cancelCarousel').click(function(){
        $('#photoHelper').hide();
        $('#photo').show();
        return false;
    });

  $('#photoSelectionModeSwitch').click(function(){
    autoMode = !autoMode;

    if(autoMode){
        $('#automaticPhotoSection').show();
        $('#manualPhotoSection').hide();
        $('#photoSelectionModeSwitch').html('enter a URL');
    }
    else{
        $('#automaticPhotoSection').hide();
        $('#manualPhotoSection').show();
        $('#photoSelectionModeSwitch').html('auto-suggest images');
    }
    return false;
  });

  $('#manualPhotoUrlSave').click(function(){
    var url = $('#photoUrl').val();
    if (!url || !url.match (/(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/))
        alert('invalid url');
    else
        setPhoto(url);

    return false;
  });
}

google.setOnLoadCallback(onLoad);

function loadCarousel(size)
{
    //$('#photo').hide();
    jQuery('#faces').jcarousel({
        visible:3,
        size:size,
        itemLoadCallback: {onBeforeAnimation:itemLoadCallbackFunction},
        buttonPrevHTML:'<a style="text-align:center;font-size:20px;">&laquo;</a>',
        buttonNextHTML:'<a style="text-align:center;font-size:20px;">&raquo;</a>'
    });
}


function itemLoadCallbackFunction(carousel, state)
{
    for (var i = carousel.first; i <= carousel.last; i++) {
        if (carousel.has(i)) {
            continue;
        }

        if (i <= mycarousel_itemList.length) {
            carousel.add(i, mycarousel_getItemHTML(mycarousel_itemList[i-1]));
        }
    }
};

function mycarousel_getItemHTML(item)
{
    return '<a href="javascript:setPhoto(\'' + item.url + '\')"><img style="border:none;" src="' + item.thumb + '" width="100" height="100" alt="' + item.thumb + '" /></a>';
};


function setPhoto(url){
    var action = GLOBALS.contextPath+'/ajax/editSubject?addImage&subjectId=' + GLOBALS.sid + '&imageUrl=' + encodeURIComponent(url) + '&formatted=true';

    $.ajax({
        type: 'POST', dataType: 'json', cache: false, url: action, data: [],
        success: function(data, textStatus) {
          if (!data.error && data.imageRef.url) {
            var photo = document.getElementById('photo');
            photo.onload = function(){$('#photo').show();};
            photo.src = data.imageRef.url;

            $('#photoHelper').hide();
            $('#undoImage').css('display', 'block')
            $('#undoImage').click(function(){
               undoImage(data.imageRef.id);
               return false;
            });
          }
          else {
            if (data.errors['_GLOBAL_'] && data.errors['_GLOBAL_'].length) {
              formatErrors(data.errors['_GLOBAL_']);
            }
            else {
              formatErrors(['an unknown error occurred']);
            }
          }
        },
        error: function(ajaxRequest, textStatus, errorThrown) {
          formatErrors(['an internal error occurred (' + ajaxRequest.status + ' - ' +  ajaxRequest.statusText + ')']);
        }
      });
}

function undoImage(imageId){
    var action = GLOBALS.contextPath+'/ajax/editSubject?deleteImage&subjectId=' + GLOBALS.sid + '&imageId=' + imageId + '&formatted=true';

    $.ajax({
        type: 'POST', dataType: 'json', cache: false, url: action, data: [],
        success: function(data, textStatus) {
          if (!data.error) {
            window.location.href = window.location.href;
          }
          else {
            if (data.errors['_GLOBAL_'] && data.errors['_GLOBAL_'].length) {
              formatErrors(data.errors['_GLOBAL_']);
            }
            else {
              formatErrors(['an unknown error occurred']);
            }
          }
        },
        error: function(ajaxRequest, textStatus, errorThrown) {
          formatErrors(['an internal error occurred (' + ajaxRequest.status + ' - ' +  ajaxRequest.statusText + ')']);
        }
      });
}