// This fix is only required for Firefox
// - rewritten version of cmsform() from http://www.alistapart.com/articles/prettyaccessibleforms
//   by C Kernan on 24/10/2007 to avoid having to use JQuery
function accessibleForms()
{
  var inputs, textareas
  var forms = document.getElementsByTagName('form')
  for (var i = 0; i < forms.length; i++) {
    if (forms[i].className != 'accessible') {
      continue
    }
    inputs = forms[i].getElementsByTagName('input')
    for (var j = 0; j < inputs.length; j++) {
      if (inputs[j].type != 'text' && inputs[j].type != 'password') {
        continue
      }
      inputs[j].onfocus = function () {
        this.className += ' focused'
      }
      inputs[j].onblur = function () {
        this.className = this.className.replace(/ focused/g, '')
      }
    }
    textareas = forms[i].getElementsByTagName('textarea')
    for (var j = 0; j < textareas.length; j++) {
      textareas[j].onfocus = function () {
        this.className = 'focused'
      }
      textareas[j].onblur = function () {
        this.className = null
      }
    }
  }
}

function checkForm(form)
{
  var re, match, element, elementName, elementCount, elementChecked
  var elements = getValidationElements(form)
  for (var i = 0; i < elements.length; i++) {
    // check all input type=text are not empty
    if (elements[i].type == 'text' && elements[i].value == '') {
      alert('Please complete ' + elements[i].name.replace(/_/g, ' '))
      elements[i].focus()
      return false
    // check all <input type=radio> and <input type=checkbox> have one option checked
    } else if ((elements[i].type == 'checkbox' || elements[i].type == 'radio') && !elements[i].checked) {
      // all radio and checkboxes buttons have ids ending _1 or similar
      re = new RegExp('(.+)_([0-9]+)$', 'g')
      match = re.exec(elements[i].id)
      // match[1] is element name, match[2] is element number
      if (match && parseInt(match[2]) == 1) {
        elementName = match[1]
        elementCount = 1
        elementChecked = false
        while (element = $(elementName + '_' + elementCount)) {
          if (element.checked) {
            elementChecked = true
            break
          }
          elementCount++
        }
        if (!elementChecked) {
          alert('Please select ' + elementName.replace(/_/g, ' '))
          window.location.hash = elementName + '_1'
          return false
        }
      }
    } else if (elements[i].type == 'select-one' && elements[i].options[elements[i].options.selectedIndex].value == '') {
      alert('Please select ' + elements[i].name.replace(/_/g, ' '))
      elements[i].focus()
      return false
    }
  }
  return true
}

function externalLinks()
{
  if (!document.getElementsByTagName) {
    return
  }
  var anchor
  var anchors = document.getElementsByTagName('a')
  for (var i = 0; i < anchors.length; i++) {
    anchor = anchors[i]
    if (anchor.getAttribute('href') && anchor.getAttribute('rel') == 'external') {
      anchor.target = '_blank'
    }
  }
}

function firefoxForms()
{
  if (!document.addEventListener) {
    return false
  }
  var fieldsets, labels, labelContent, labelWidth, labelSpan
  var forms = document.getElementsByTagName('form')
  for (var i = 0; i < forms.length; i++) {
    if (forms[i].className != 'accessible') {
      continue
    }
    fieldsets = forms[i].getElementsByTagName('fieldset')
    for (var j = 0; j < fieldsets.length; j++) {
      labels = fieldsets[j].getElementsByTagName('label')
      for (k = 0; k < labels.length; k++) {
        labelContent = labels[k].innerHTML
        labelWidth = labels[k].style.width
        labelSpan = document.createElement('span')
        labelSpan.style.display = 'block'
        labelSpan.style.width = document.defaultView.getComputedStyle(labels[k], '').getPropertyValue('width')
        labelSpan.innerHTML = labelContent
        labels[k].style.display = '-moz-inline-box'
        labels[k].innerHTML = null
        labels[k].appendChild(labelSpan)
      }
    }
    forms[i].style.display = 'block'
  }
}

function getValidationElements(root)
{
  // Iteratively traverse DOM starting from root given and return an array of form element objects with class="required"
  var count = 0
  var s = ''
  var c = root, n = null
  var validateElements = []
  do {
    n = c.firstChild
    if (n == null) {
      if (c.nodeType == 1 && c.className.indexOf('required') != -1 && (c.tagName.toUpperCase() == 'INPUT' || c.tagName.toUpperCase() == 'TEXTAREA' || c.tagName.toUpperCase() == 'SELECT')) {
        validateElements[count++] = c
      }
      n = c.nextSibling
    }
    if (n == null) {
      var tmp = c
      do {
        n = tmp.parentNode
        if (n == root) {
          break
        }
        if (n.nodeType == 1 && n.className.indexOf('required') != -1 && (n.tagName.toUpperCase() == 'INPUT' || n.tagName.toUpperCase() == 'TEXTAREA' || n.tagName.toUpperCase() == 'SELECT')) {
          validateElements[count++] = n
        }
        tmp = n
        n = n.nextSibling
      } while (n == null)
    }
    c = n
  } while (c != root)
  return validateElements
}

function pngFix()
{
  // IE6 only
  if (typeof document.body.style.maxHeight != 'undefined' || !document.all) {
    return
  }
  for (var i = 0; i < document.images.length; i++) {
    var img = document.images[i]
    var imgName = img.src.toUpperCase()
    if (imgName.substring(imgName.length-3, imgName.length) == "PNG") {
      var imgID = (img.id) ? "id='" + img.id + "' " : ""
      var imgClass = (img.className) ? "class='" + img.className + "' " : ""
      var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
      var imgStyle = "display:inline-block;" + img.style.cssText
      if (img.align == "left") imgStyle = "float:left;" + imgStyle
      if (img.align == "right") imgStyle = "float:right;" + imgStyle
      if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
      var strNewHTML = "<span " + imgID + imgClass + imgTitle
      + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
      + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
      + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
      img.outerHTML = strNewHTML
      i = i - 1
    }
  }
}

function menuFix()
{
  // non IE browsers and IE8 return
  if (typeof document.body.style.borderSpacing != 'undefined' || !document.all) {
    return false
  }
  var listItems = document.getElementById('nav').getElementsByTagName('LI')
  for (var i = 0; i < listItems.length; i++) {
    listItems[i].onmouseover = function() {
      this.className += ' hover'
    }
    listItems[i].onmouseout = function() {
      this.className = this.className.replace(new RegExp(' hover\\b'), '')
    }
  }
}

if (typeof jQuery != 'undefined') {
  // Show new development announcement using slide down effect 1 second after dom is loaded
  $(function(){
    pngFix()
    menuFix()
    setTimeout(function() {
      $('#announcement p').text('')
      $('#announcement p').click(function(){ window.location='/lease/' })
      $('#announcement p').slideDown(1500)
    }, 1250)
  });
  // Change horizontal position of sunburst background on load of site
  $(function(){
    var w = $(window).width() >= 990 ? $(window).width() : 990;
    var x = Math.ceil((w - 1280) / 2)
    $('#outer').css('background-position', x + 'px 5px')
  });
  // Change horizontal position of sunburst background on resize of site
  // background image is 1280px wide, site is 990px wide
  $(window).resize(function(){
    var w = $(window).width() >= 990 ? $(window).width() : 990;
    var x = Math.ceil((w - 1280) / 2)
    $("#outer").css('background-position', x + 'px 5px')
  });
  // Load google map
  $(function(){
    if (document.getElementById('googlemap')) {
      var mapOptions = {
        zoom: 16,
        center: new google.maps.LatLng(53.391, -2.5885),
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      var map = new google.maps.Map(document.getElementById('googlemap'), mapOptions);
      // shopping centre overlay image
      var shoppingAreaImage = new google.maps.MarkerImage('/images/map-shopping-area.png',
        new google.maps.Size(309, 154), // size
        new google.maps.Point(0, 0),    // origin
        new google.maps.Point(0, 0)     // anchor
      );
      var shoppingAreaImageOutline = new google.maps.MarkerImage('/images/map-shopping-area-outline.png',
        new google.maps.Size(309, 154), // size
        new google.maps.Point(0, 0),    // origin
        new google.maps.Point(0, 0)     // anchor
      );
      // shopping centre overlay image
      var logoImage = new google.maps.MarkerImage('/images/map-cockhedgelogo.png',
        new google.maps.Size(53, 42),   // size
        new google.maps.Point(0, 0),    // origin
        new google.maps.Point(0, 0)     // anchor
      );
      // add shopping centre overlay to map
      var shoppingArea = new google.maps.Marker({
        position: new google.maps.LatLng(53.39226, -2.59329),
        map: map,
        icon: shoppingAreaImage,
        clickable: false,
        title: 'Cockhedge Shopping Park',
        visible: true
      });
      var shoppingAreaOutline = new google.maps.Marker({
        position: new google.maps.LatLng(53.39226, -2.59329),
        map: map,
        icon: shoppingAreaImageOutline,
        clickable: false,
        title: 'Cockhedge Shopping Park',
        visible: false
      });
      var logo = new google.maps.Marker({
        position: new google.maps.LatLng(53.3915, -2.591),
        map: map,
        icon: logoImage,
        clickable: false,
        title: 'Cockhedge Shopping Park',
        visible: true
      });
      // ensure overlay is only shown for zoom level 16
      google.maps.event.addListener(map, 'zoom_changed', function() {
        var zoomLevel = map.get_zoom();
        var mapType = map.get_mapTypeId();
        if (zoomLevel != 16) {
          shoppingArea.visible = false
          shoppingAreaOutline.visible = false
          logo.visible = true
        } else {
          if (mapType == 'satellite') {
            shoppingAreaOutline.visible = true
            shoppingArea.visible = false
          } else {
            shoppingAreaOutline.visible = false
            shoppingArea.visible = true
          }
          logo.visible = true
        }
      });
      google.maps.event.addListener(map, 'mapTypeId_changed', function() {
        //SATELLITE
        var mapType = map.get_mapTypeId();
        var zoomLevel = map.get_zoom();
        if (mapType == 'satellite' && zoomLevel == 16) {
          shoppingAreaOutline.visible = true
          shoppingArea.visible = false
        } else {
          shoppingAreaOutline.visible = false
          shoppingArea.visible = true
        }
      });
    }
  });
  // toggle store categories
  $(function(){
    if (document.getElementById('category-list')) {
      // hide all stores within each category initially
      $('#category-list ul ul:not(.selected)').hide()
      // toggle display of stores for each category when clicked
      $('#category-list ul:first > li > a').click(function(e) {
        e.preventDefault()
        $(this).parent().find('ul').each(function() {
          $(this).slideToggle('slow')
        });
      });
    }
  });
  // cross browser bookmark
  $(function(){
    // add a "rel" attrib if Opera 7+
    if(window.opera) {
      if ($("a.jqbookmark").attr("rel") != "") { // don't overwrite the rel attrib if already set
        $("a.jqbookmark").attr("rel","sidebar");
      }
    }
    $("a.jqbookmark").click(function(event) {
      event.preventDefault(); // prevent the anchor tag from sending the user off to the link
      var url = this.href;
      var title = this.title;
      if (window.sidebar) { // Mozilla Firefox Bookmark
        window.sidebar.addPanel(title, url,"");
      } else if( window.external ) { // IE Favorite
        window.external.AddFavorite( url, title);
      } else if(window.opera) { // Opera 7+
        return false; // do nothing - the rel="sidebar" should do the trick
      } else { // for Safari, Konq etc - browsers who do not support bookmarking scripts (that i could find anyway)
        alert('Unfortunately, this browser does not support the requested action,' + ' please bookmark this page manually.');
      }
    });
  });

  $(function(){
    if ($('#offers').get().length > 0) {
      $('#offers div.bottom').each(function() {
        if (!$(this).hasClass('first')) {
          $(this).hide()
        }
      });
      $('#offers div.top').mouseover(function(event){
        $(this).css('cursor', 'pointer')
      });
      $('#offers div.top').click(function(event) {
        $(this).next('div.bottom').slideToggle('slow')
      });
    }
  });
  $(function(){
		if (document.getElementById('slider')) {
      $("#slider").easySlider({
  			auto: true,
  			continuous: true,
  			controlsShow: false,
  			pause: 3000
  		});
  	}
	});
	// hide form labels on foxus
	$(function(){
    $('input.register_name').focus(function(){
      if ($(this).attr('value') == 'Name') {
        $(this).attr('value', '')
      }
    })
    $('input.register_name').blur(function(){
      if ($(this).attr('value') == '') {
        $(this).attr('value', 'Name')
      }
    })
    $('input.register_email').focus(function(){
      if ($(this).attr('value') == 'Email Address') {
        $(this).attr('value', '')
      }
    })
    $('input.register_email').blur(function(){
      if ($(this).attr('value') == '') {
        $(this).attr('value', 'Email Address')
      }
    })
	});
	// manage email a friend box
	$(function(){
    $('#send-friend').click(function(event) {
      event.preventDefault();
      var buttonPosition = $(this).position()
      $('#email-friends-box').css({'left': buttonPosition.left + 'px', 'top': (buttonPosition.top - 100) + 'px', 'display': 'block'})
      $('#email-friends-box').animate({ width: '250px', height: '200px'})
    });
    $('#email-friends-box input#cancel').click(function(){
      $('#email-friends-box').css({'width': '50px', 'height': '50px', 'display': 'none'})
    });
  });
  $(function(){
    var slideshowId
    $('div.smoothgallery').each(function() {
      slideshowId = $(this).attr('id')
        new gallery(Moo.$(slideshowId), {
    		elementSelector: 'div.slide',
        titleSelector: 'h2',
        timed: true,
    		delay: 5000,
    		embedLinks: false,
    		showInfopane: true,
    		showArrows: false
    	});
    });
  });
  // fade out instructions and error messages
  $(function(){
    $('#instructions').fadeOut(8000)
    if (document.getElementById('errors') && $('#errors').hasClass('fade')) {
      $('#errors').fadeOut(8000)
    }
  });
  $(function() {
    if ($("#features ul").get().length > 0) {
      $("#features ul").newsticker(6000)
    }
  });
}