var imageFlowInstance = null;

$(document).ready( function() {
  $("#welcomebtn").click(function () {
      $("#welcomemsg").slideUp();
  });

  /* Form Code */
  $("#freeGuideForm").submit(function(){
    if ($("#g_name").val()=='') $("#g_name_li").effect("shake", { times: 3 }, 100);
    else if ($("#g_mobile").val()=='') $("#g_mobile_li").effect("shake", { times: 3 }, 100);
    else if ($("#g_email").val()=='') $("#g_email_li").effect("shake", { times: 3 }, 100);
    else return true;
    return false;
  }); 

  $("#enquiryForm").submit(function(){
    if ($("#e_name").val()=='') $("#e_name_li").effect("shake", { times: 3 }, 100);
    else if ($("#e_mobile").val()=='') $("#e_mobile_li").effect("shake", { times: 3 }, 100);
    else if ($("#e_email").val()=='') $("#e_email_li").effect("shake", { times: 3 }, 100);
    else return true;
    return false;
  });

  $("#emailFriendForm").submit(function(){
    if ($("#my_name").val()=='') $("#my_name_li").effect("shake", { times: 3 }, 100);
    else if ($("#friend_name").val()=='') $("#friend_name_li").effect("shake", { times: 3 }, 100);
    else if ($("#friend_email").val()=='') $("#friend_email_li").effect("shake", { times: 3 }, 100);
    else return true;
    return false;
  });

  $("#competitionForm").submit(function(){
    if ($("#r_fname").val()=='') $("#r_fname_li").effect("shake", { times: 3 }, 100);
    else if ($("#r_lname").val()=='') $("#r_lname_li").effect("shake", { times: 3 }, 100);
    else if ($("#r_email").val()=='') $("#r_email_li").effect("shake", { times: 3 }, 100);
    else if ($("#r_mobile").val()=='') $("#r_mobile_li").effect("shake", { times: 3 }, 100);
    else if ($("#r_postcode").val()=='') $("#r_postcode_li").effect("shake", { times: 3 }, 100);
    else return true;
    return false;
  });

  $("#rsvpForm").submit(function(){
    $("#nog").val($("#guests").val());
    $("#hhr").val($("#how").val());

    if ($("#first-name").val()=='') $("#first-name-li").effect("shake", { times: 3 }, 100);
    else if ($("#last-name").val()=='') $("#last-name-li").effect("shake", { times: 3 }, 100);
    else if ($("#email").val()=='') $("#email-li").effect("shake", { times: 3 }, 100);
    else if ($("#work-phone").val()=='') $("#work-phone-li").effect("shake", { times: 3 }, 100);
    else if ($("#mobile").val()=='') $("#mobile-li").effect("shake", { times: 3 }, 100);
    else if ($("#postcode").val()=='') $("#postcode-li").effect("shake", { times: 3 }, 100);
    else return true;
    return false;
  });

  /* Gallery Code */
  $("#showAdv").click(function(){
    $("#advancedSearch").slideToggle(400);
    return false;
  });

  $('#cf').click(function() { 
    $("#cf").addClass('current');
    $("#gr").removeClass('current');
    $("#content").removeClass('three'); 
    $("#galleryGrid").hide();
    $(".artworksPageNav").hide();
    searchRefresh(true);
//    $("#imageFlowContainer").fadeIn(400);
    return false;
  });

  $('#gr').click(function() { 
    $("#cf").removeClass('current');
    $("#gr").addClass('current');
    $("#content").addClass('three'); 
    $("#imageFlowContainer").hide();
    $(".artworksPageNav").show();
    $("#galleryGrid").fadeIn(400);
    return false;
  });

  $('a.backArtworks').click(function() {
    var startId = updateStartId(-9);
    $.scrollTo("#content");
    searchRefresh(true);
    if(startId <= 0) $('a.backArtworks').hide();
    return false;
  });

  $('a.moreArtworks').click(function(e) {
    e.preventDefault();
    updateStartId(9);
    $.scrollTo("#content");
    searchRefresh(true);
    $('a.backArtworks').show();
    return false;
  });

  $('#quickfind').change(
    function() {
     $('#artist').val($('#quickfind').val());
     searchRefresh();
     saveSearchOptions();
    }
  ); 

  $('#artist').change(
    function() {
     $('#quickfind').val($('#artist').val());
     searchRefresh();
     saveSearchOptions();
    }
  );

  $('#price').change(function(){searchRefresh(); saveSearchOptions();}); 
  $('#medium').change(function(){searchRefresh(); saveSearchOptions();}); 
  $('#genre').change(function(){searchRefresh(); saveSearchOptions();}); 
  $('#characteristic').change(function(){searchRefresh(); saveSearchOptions();}); 
  $('#style').change(function(){searchRefresh(); saveSearchOptions();}); 
  $('#career').change(function(){searchRefresh(); saveSearchOptions();}); 
  $('#size').change(function(){searchRefresh(); saveSearchOptions();}); 
  $('#colour').change(function(){searchRefresh(); saveSearchOptions();}); 

  // discard the startId cookie unless we're on an art, or gallery page
  if(/^http:\/\/(.*?)\/art\//.test(document.location)) {}
  else if($('#startId').length > 0) {}
  else {
    updateStartId();
  }

  loadSearchOptions();

  if(anyAdvancedSearchOptionsSet())
    $('#advancedSearch').show();

  // switch to cover flow if needed
  if(getViewType() == 'cf')
    $('#cf').click();

  // set the hidden startId field to the cookie value, and
  // change to the appropriate page, if needed
  var startId = updateStartId(0);
  $('#startId').val(startId);
  searchRefresh(true);
  if(startId > 0) {
    $('a.backArtworks').show();
  }
});

function updateStartId(changeBy, directAssignment) {
  var cookieId;
  var cookieStartId;
  var newStartId;

  if($('#rental').val() == 'true')
    cookieId = 'startIdRental';
  else
    cookieId = 'startIdBuyers';

  cookieStartId = parseInt($.cookie(cookieId));
  if(!isFinite(cookieStartId)) cookieStartId = 0;

  changeBy = parseInt(changeBy);

  if(isFinite(changeBy)) {
    if(directAssignment === true)
      newStartId = changeBy;
    else
      newStartId = cookieStartId + changeBy;
  } else {
    newStartId = 0;
  }

  if(newStartId < 0) newStartId = 0;

  $.cookie(cookieId, newStartId, {"path":"/"});

  return newStartId;
}

function updateViewType(viewType) {
  var cookieId;

  if($('#rental').val() == 'true')
    cookieId = 'viewTypeRental';
  else
    cookieId = 'viewTypeBuyers';

  $.cookie(cookieId, viewType, {"path":"/"});
}

function getViewType() {
  var cookieId;

  if($('#rental').val() == 'true')
    cookieId = 'viewTypeRental';
  else
    cookieId = 'viewTypeBuyers';

  return $.cookie(cookieId);
}

function searchRefresh(keepPage) {
  var startId;
  if(keepPage) 
    startId = updateStartId(0);
  else
    startId = updateStartId();

  $('#startId').val(startId); // Use whatever the cookie is set to
  if(startId <= 0) $('a.backArtworks').hide(); else $('a.backArtworks').show();

  $("#imageFlowContainer").hide();
  $("#galleryGrid").hide();
  $("#loadIndicator").show();
  $("#galleries").load('/galajax/?r='+$('#rental').val()+'&a='+$('#quickfind').val()
                      +'&p='+urlencode($('#price').val())
                      +'&m='+urlencode($('#medium').val())
                      +'&g='+urlencode($('#genre').val())
                      +'&c='+urlencode($('#characteristic').val())
                      +'&s='+urlencode($('#style').val())
                      +'&ca='+urlencode($('#career').val())
                      +'&si='+urlencode($('#size').val())
                      +'&co='+urlencode($('#colour').val())
                      +'&st='+urlencode($('#startId').val()), '', 
  function(responseText) {
    var instanceOne = new ImageFlow();
    imageFlowInstance = instanceOne;
    instanceOne.init({ ImageFlowID:'myImageFlow', reflections: false, reflectionP: 0.4, opacity: true, imageFocusM: 1, xStep: 100, startID: updateStartId(0)+1 });
    $('#myImageFlow_images > img').click(function() {
      updateStartId(instanceOne.imageID, true);
      updateViewType('cf');
    });
    $('#galleryGrid a').click(function() {
      updateViewType('gr');
    });

    $("#loadIndicator").hide();

    if($('.thereAreMore').length > 0)
      $('.moreArtworks').show();
    else
      $('.moreArtworks').hide();

    if ($("#cf").hasClass('current'))
      $("#imageFlowContainer").fadeIn(400);
    else
      $("#galleryGrid").fadeIn(400);
    }
  );
}

function saveSearchOptions() {
  var cookieId;
  var searchOptions = {
    artist: $('#quickfind').val(),
    price: $('#price').val(),
    medium: $('#medium').val(),
    genre: $('#genre').val(),
    characteristic: $('#characteristic').val(),
    style: $('#style').val(),
    career: $('#career').val(),
    size: $('#size').val(),
    colour: $('#colour').val()
  };

  if($('#rental').val() == 'true')
    cookieId = 'searchOptionsRental';
  else
    cookieId = 'searchOptionsBuyers';

  $.cookie(cookieId, JSON.stringify(searchOptions), {path:"/"});
}

function loadSearchOptions() {
  var cookieId;
  var jsonData;

  if($('#rental').val() == 'true')
    cookieId = 'searchOptionsRental';
  else
    cookieId = 'searchOptionsBuyers';

  jsonData = $.cookie(cookieId);
  if(typeof(jsonData) != 'string') return;

  JSON.parse(jsonData, function(key, value) {
    switch(key) {
    case 'artist':
      $('#quickfind').val(value);
      $('#artist').val(value);
      break;
    case 'price': $('#price').val(value); break;
    case 'medium': $('#medium').val(value); break;
    case 'genre': $('#genre').val(value); break;
    case 'characteristic': $('#characteristic').val(value); break;
    case 'style': $('#style').val(value); break;
    case 'career': $('#career').val(value); break;
    case 'size': $('#size').val(value); break;
    case 'colour': $('#colour').val(value); break;
    }
  });
}

function urlencode(str) {
  return escape(str).replace('+', '%2B').replace('%20', '+').replace('*', '%2A').replace('/', '%2F').replace('@', '%40');
}

function anyAdvancedSearchOptionsSet() {
  var activeOptions = $('#price, #medium, #genre, #characteristic, #style, #career, #size, #colour').filter(function() {
    return $(this).val() != 'Any';
  });

  return activeOptions.length > 0;
}

