var disableRightClick = false;

function validateInputField(jqField, classIfEmpty)
{
  var valid = false;
  if(jqField.val() == '')
  {
    jqField.addClass(classIfEmpty);
  }else
  {
    jqField.removeClass(classIfEmpty);
    valid = true;
  }
  return valid;
}

/*-------------------------------------------------------
 * Onload sound integration
 */

function onSoundStopOrFinish(soundId)
{
	 soundManager.getSoundById(soundId).stop();
	 $('#'+soundId+'_pause').hide();
	 $('#'+soundId+'_play').show();
}
 
function playBgSoundAndAddPlayer(playerHtmlId, soundId, srcUrl, 
																	apiSwfUrl, playImgUrl, pauseImgUrl, 
																	stopImgUrl, autostart)
{
   soundManager.url = apiSwfUrl;
   soundManager.debugMode = false;
   soundManager.consoleOnly = false;
	 soundManager.onload = function() 
	 {
		  var mySound = soundManager.createSound({
		    id: soundId,
		    url: srcUrl,
		    volume: 50,
		    onfinish: function()
		    {
		  	  onSoundStopOrFinish(soundId)
		    }
		  });
		  
		  var playDisplay  = autostart ? 'display: none;' : '';
		  var pauseDisplay = autostart ? '' : 'display: none;';
		  
		  //Play button
		  var controls = '<img src="'+playImgUrl+'" class="MiniPlayerControl" id="'+soundId+'_play"';
		  controls    += ' onclick="soundManager.getSoundById(\''+soundId+'\').play();$(\'#'+soundId+'_pause\').show();$(\'#'+soundId+'_play\').hide();"';
		  controls    += ' style="'+playDisplay+'" />';
		  
		  //Pause button
		  controls    += '<img src="'+pauseImgUrl+'" class="MiniPlayerControl" id="'+soundId+'_pause"';
		  controls    += ' onclick="soundManager.getSoundById(\''+soundId+'\').pause();$(\'#'+soundId+'_pause\').hide();$(\'#'+soundId+'_play\').show();"';
		  controls    += ' style="'+pauseDisplay+'" />';
		  
		  //Stop button
		  controls    += '<img src="'+stopImgUrl+'" class="MiniPlayerControl" id="'+soundId+'_stop"';
		  controls    += ' onclick="onSoundStopOrFinish(\''+soundId+'\');" />';
		  if(autostart)
		  {
		    mySound.play();
		  }
		  $('#'+playerHtmlId).html(controls);
	}
}

/*-------------------------------------------------------
 * WorldPay integration
 */
function displayCardsIfWorldPay(cb)
{
	if(cb.value == 'checkout_worldpay')
	{
		$('#WorldPayAuthorizedCreditCards').show();
	}else
	{
		$('#WorldPayAuthorizedCreditCards').hide();
	}
}


/*-------------------------------------------------------
 * Tell a friend integration
 * Thanks to http://ericmmartin.com for its modal popup examples
 */

function validateTellAFriendForm()
{
  var returnValue = true;
  var selfNameField     = $('#modal-popup-container #self_name');
  var selfEmailField    = $('#modal-popup-container #self_email');
  var friendsNameField  = $('#modal-popup-container #friends_name');
  var friendsEmailField = $('#modal-popup-container #friends_email');

  returnValue = validateInputField(selfNameField, 'modal-popup-required-field');
  returnValue = validateInputField(selfEmailField, 'modal-popup-required-field') && returnValue;
  returnValue = validateInputField(friendsNameField, 'modal-popup-required-field') && returnValue;
  returnValue = validateInputField(friendsEmailField, 'modal-popup-required-field') && returnValue;

  if(!returnValue)
  {
    returnValue = lang.TellAFriendMissingRequiredField;
  }
  return returnValue;
}

function attachTellAFriendEvents(dialog, productId)
{
  $('#modal-popup-container #go_tell_a_friend_button').click(function (e) 
  {
    e.preventDefault();
    
    var validationReturn = validateTellAFriendForm();
    if (validationReturn === true) 
    {
      $('#modal-popup-container .modal-popup-error').fadeOut(200, 
        function() 
        {
          $('#modal-popup-container .modal-popup-error').empty();
        });
      $('#modal-popup-container .modal-popup-title').html(lang.TellAFriendSending + '...');
      //$('#modal-popup-container form').fadeOut(200);
      //$('#modal-popup-container form').empty();
      $('#modal-popup-container form').hide();
      $('#modal-popup-container .modal-popup-content').animate({
        height: '120px'
      }, function () {
        $('#modal-popup-container .modal-popup-loading').fadeIn(200, function () {
          $.ajax({
            url: '/tellafriend.php',
            data: $('#modal-popup-container form').serialize() + '&action=send&product_id=' + productId,
            type: 'post',
            cache: false,
            dataType: 'html',
            success: function (response, statusText) {
              $('#modal-popup-container .modal-popup-loading').fadeOut(200, function () {
                $('#modal-popup-container .modal-popup-title').html(lang.TellAFriendEndTitle);
                $('#modal-popup-container .modal-popup-message').html(response);
                $('#modal-popup-container .modal-popup-message').fadeIn(200);
              });
            },
            error: function (req, textStatus, errorThrown){ defaultAjaxErrorPopup(req, textStatus, errorThrown, lang.AjaxError); }
          });
        });
      });
    }
    else 
    {
      if ($('#modal-popup-container .modal-popup-error:visible').length > 0) 
      {
        var msg = $('#modal-popup-container .modal-popup-error');
        msg.fadeOut(200, 
          function () 
          {
            msg.empty();
            msg.html(validationReturn);
            msg.fadeIn(200);
          });
      }
      else 
      {
        $('#modal-popup-container .modal-popup-error').animate({
          height: '18px'
        }, function (){ $('#modal-popup-container .modal-popup-error').html(validationReturn); } );
      }
      
    }
  });
}

function tellAFriend(productId)
{
  var url = "/tellafriend.php?product_id=" + productId; 
  $.get(url, function(data){
    // Creates a modal dialog with the data
    $(data).modal({
      close: false,
      position: ["15%",],
      overlayId: 'modal-popup-overlay',
      containerId: 'modal-popup-container',
      onOpen: function (dialog) {openModalPopup(dialog, 310); },
      onShow: function (dialog) {attachTellAFriendEvents(dialog, productId); },
      onClose: closeModalPopup
    });
  });
}

function openModalPopup(dialog, height) 
{
  var title = $('#modal-popup-container .modal-popup-title').html();
  $('#contact-container .modal-popup-title').html(lang.Loading+'...');
  dialog.overlay.fadeIn(200, function () 
  {
    dialog.container.fadeIn(200, function () 
    {
      dialog.data.fadeIn(200, function () 
      {
        $('#modal-popup-container .modal-popup-content').animate(
        {
          height: height
        }, 
        function () 
        {
          $('#modal-popup-container .modal-popup-title').html(title);
          $('#modal-popup-container form').fadeIn(200, 
          function () 
          {
            //$('#contact-container #contact-name').focus();
          });
        });
      });
    });
  });
}

function closeModalPopup(dialog) 
{
  $('#modal-popup-container .modal-popup-message').fadeOut();
  $('#modal-popup-container form').fadeOut(200);
  $('#modal-popup-container .modal-popup-content').animate(
  {
    height: 30
  }, 
  function () 
  {
    $.modal.close();
    //dialog.overlay.fadeOut(200, function (){$.modal.close();}); 
  });
}

/*-------------------------------------------------------
 * Postcode Finder integration
 */
//Display or not find button if uk selected
function onCountryChanged(selectElement, findBtnId)
{
	var isUK = selectElement.options[selectElement.selectedIndex].value.toLowerCase() == 'united kingdom'; 
	var findBtn = document.getElementById(findBtnId);
	if(isUK)
	{
		findBtn.style.display = 'inline';
	}else
	{
		findBtn.style.display = 'none';
	}
}

//Find matches from post code (contained in given input) 
function findPostCode(inputId,resultsPanelId, addr1Id, addr2Id, stateId, cityId)
{
  var inputElement = document.getElementById(inputId);
  var postcode = inputElement.value;
  
  if(postcode == '')
  {
  	alert(lang.PostCodeFinderEmptyCodeMessage);
  }else
  {
	  //Post ajax request
	  $.ajax({
	    url: 'postcodefinder.php',
	    type: 'POST',
	    data: {PostCode:postcode, Mode:'Search', Address1HtmlId:addr1Id, 
				Address2HtmlId:addr2Id, StateHtmlId:stateId,
				CityHtmlId:cityId},
	    dataType: 'xml',
	    success: function(response){onPostCodeMatchFound(response,resultsPanelId);},
	    error: function (req, textStatus, errorThrown){ defaultAjaxErrorPopup(req, textStatus, errorThrown, lang.AjaxError); }
	  });
  }
}

//Call back when findPostCode matches found
function onPostCodeMatchFound(response, resultsPanelId)
{
  var matchesTag          = response.getElementsByTagName('Matches');
  var matchContentTag     = matchesTag[0];
  var resultsPanelElement = document.getElementById(resultsPanelId);
  
  resultsPanelElement.innerHTML = matchContentTag.firstChild.data;
}

//Requests for informations about selected address to fill form
function onPostCodeResultSelected(selectResultElement, addr1Id, addr2Id, stateId, cityId)
{
	var iSelected = selectResultElement.selectedIndex;
	var addressId = selectResultElement.options[iSelected].value;
	
	if(addressId == '')
	{
		document.getElementById(addr1Id).value = '';
	  document.getElementById(addr2Id).value = '';
	  document.getElementById(stateId).value = ''; 
	  document.getElementById(cityId).value  = '';
	}else
	{
		$.ajax({
	    url: 'postcodefinder.php',
	    type: 'POST',
	    data: {Mode:'AddressDetails', AddressId:addressId},
	    dataType: 'xml',
	    success: function(response){onAddressDetailsReceived(response,addr1Id,addr2Id,stateId,cityId);},
	    error: function (req, textStatus, errorThrown){ defaultAjaxErrorPopup(req, textStatus, errorThrown, lang.AjaxError); }
	  });
	}
}

//Fills form
function onAddressDetailsReceived(response, addr1Id, addr2Id, stateId, cityId)
{
	var matchesTag          = response.getElementsByTagName('Address');
  var matchContentTag     = matchesTag[0];
  
  var addr1 = matchContentTag.getElementsByTagName('Line1');
  var addr2 = matchContentTag.getElementsByTagName('Line2');
  var state = matchContentTag.getElementsByTagName('State');
  var city  = matchContentTag.getElementsByTagName('Suburb');
  
//  alert(addr1.length);
//  alert(addr2.length);
//  alert(state.length);
//  alert(city.length);
  
  document.getElementById(addr1Id).value = addr1[0].firstChild.data;
  document.getElementById(addr2Id).value = addr2[0].firstChild.data;
  document.getElementById(stateId).value = state[0].firstChild.data; 
  document.getElementById(cityId).value  = city[0].firstChild.data;
}

function defaultAjaxErrorPopup(req, textStatus, errorThrown, msg)
{
  alert(msg + errorThrown+' - '+textStatus);
}

/*-------------------------------------------------------
 * Allows bookmarks creation under ff and ie
 */
function addBookmark(url, desc)
{
	var bookmarkurl = url;
	var bookmarktitle = desc;
	var nonie = lang.CantBookmarkUnsupported;

	if (window.sidebar)
	{
		//Mozilla Firefox Bookmark
		window.sidebar.addPanel(bookmarktitle, bookmarkurl, "");
	} else
	{
		if (navigator.appName == "Microsoft Internet Explorer")
		{
			// IE Favourites
			window.external.AddFavorite(bookmarkurl, bookmarktitle);
		} else
		{
			alert(nonie);
		}
	}
}

/*----------------------------------
 * Disable right mouse click Script
 */
// By Maximus (maximus@nsimail.com) w/ mods by DynamicDrive
// For full source code, visit http://www.dynamicdrive.com
var message = lang.RightClickMessage;

function clickIE4()
{
	if (event.button == 2)
	{
		alert(message);
		return false;
	}
}

function clickNS4(e)
{
	if (document.layers || document.getElementById && !document.all)
	{
		if (e.which == 2 || e.which == 3)
		{
			alert(message);
			return false;
		}
	}
}

if (disableRightClick)
{
	if (document.layers)
	{
		document.captureEvents(Event.MOUSEDOWN);
		document.onmousedown = clickNS4;
	} else
	{
		if (document.all && !document.getElementById)
		{
			document.onmousedown = clickIE4;
		}
	}
	document.oncontextmenu = new Function("alert(message);return false")
}
