$(function() {

    /* Change font size */
    $('.changeFontSize').click(function() {
        changeFontSize($(this).attr("rel"));
        return false;
    })

    /* Set up show/hide access key stuff */
    var accessKeysOn;
    $('.toggleAccessKeys').click(function() {
        if (accessKeysOn) {
            $("LINK[href='/styles/access-keys.css']").remove();
            accessKeysOn = 0;
        } else {
            $('head').append('<link rel="stylesheet" href="/styles/access-keys.css" type="text/css" id="contrastStylesheet" />');
            accessKeysOn = 1;
        }

    });

    /* Change to high contrast stylesheet */
    $('.toggleHighContrast').click(function() {
       var contrastCookie = readCookie('contrastCookie');
       if (contrastCookie == 'on') {
           $("LINK[href='/styles/high-contrast.css']").remove();
            createCookie('contrastCookie', 'off', 365)
            $('#phoneIcon').attr('src','/images/phone-icon.gif');
            $('#contactaLogo').attr('src','/images/contacta-logo.gif');
            $('.searchSubmit').css('background-image','url(/images/search-button.gif)');
       } else {
           $('head').append('<link rel="stylesheet" href="/styles/high-contrast.css" type="text/css" id="contrastStylesheet" />');
            createCookie("contrastCookie", "on", 365);
            $('#phoneIcon').attr('src','images/contrast/phone-icon.gif');
            $('#contactaLogo').attr('src','/images/contrast/contacta-logo.gif');
            $('.searchSubmit').css('background-image','url(/images/contrast/search-button.gif)');
       }
    });

    //Set stylesheet if cookie is set
    var contrastCookie = readCookie('contrastCookie');
    if (contrastCookie == 'on') {
        $('head').append('<link rel="stylesheet" href="/styles/high-contrast.css" type="text/css" id="contrastStylesheet" />');
        $('#phoneIcon').attr('src','/images/contrast/phone-icon.gif');
        $('#contactaLogo').attr('src','/images/contrast/contacta-logo.gif');
        $('.searchSubmit').css('background-image','url(/images/contrast/search-button.gif)');
    }
    

    /* Set up skip navigation link anchor */
    

	/* Setup links that automatically popup in a new window */
	$('a[rel=external]').popupLinks();

	/* Setup input fields that clear the text when you focus them */
        $('.autoclear').autoClear();

	/* Setup friendly HTML forms, highlights and focus */
        $('.friendlyForm').formSetup();

	/* Setup print page functionality */
	$('.printPage').printPage();

        $('#tabs').tabs();

        $('#clientLogos').cycle({
            fx: 'fade',
            timeout: 5000
        });

        /* Change all uiButtons */
        $('.uiButton').button();

        /* Login form modal */
        $('.signIn a').click(function() {
            $('#modalLoginForm').toggle();
            return false;
        });

        /* Close login Modal */
        $('.closeModal').click(function() {
            $('#modalLoginForm').toggle();
            return false;
        })

        /* Table stripes */
	$('table.stripe tbody tr:odd').addClass('stripe');

        /* Google Maps Configuration */
        if ($('#map').length != 0) {
            var myLatlng = new google.maps.LatLng(51.276441,0.400786);
            var myOptions = {
              zoom: 14,
              center: myLatlng,
              mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            var map = new google.maps.Map(document.getElementById("map"), myOptions);

            var contentString = [
                '<div id="tabs">',
                    '<ul>',
                        '<li><a href="#tab-1"><span>Location</span></a></li>',
                        '<li><a href="#tab-2"><span>Directions</span></a></li>',
                    '</ul>',
                    '<div id="tab-1" class="tabContent">',
                        '<p><strong>Contacta Limited</strong><br />11 Tower View<br />Kings Hill<br />West Malling<br />Kent<br />ME19 4UY<br /><br />Tel: 01732 223 900<br />Fax: 01732 223 909</p>',
                    '</div>',
                    '<div id="tab-2" class="tabContent">',
                        '<p>Get driving directions to the Contacta office simply by entering your postcode below<br><br><input style="font-size: 10px;" type="text" id="postcode">&nbsp;<input type="button" style="font-size:10px;" onclick="getDirections();" value="Go"><br /><br />(you will need to enable popups for this to work correctly)</p>',
                    '</div>',
                '</div>'
            ].join('');

            var infowindow = new google.maps.InfoWindow({
                content: contentString,
                maxWidth: 400
            });

            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                title: "Contacta"
            });
            google.maps.event.addListener(marker, 'click', function() {
              infowindow.open(map,marker);
              $("#tabs").tabs();
            }); 
        }

        if (getParameterByName('q')) {
            /* Highlight the search terms of the search results page */
            $("#searchResults").highlight(getParameterByName('q'), 1, "searchHighlight");
        }

        /* Customer account creation validation */
        if ($('#accountForm').length != 0) {
           /* Check password strength */
           $("#password").passStrength({
                userid:	"#emailAddress"
            });
            /* Front end validation */
            $('h2.messageText').hide();
            jQuery.validator.messages.required = "";  //Defines that the error labels are populated.
            $('#accountForm').validate({
                invalidHandler: function(form, validator) {
                  var errors = validator.numberOfInvalids();
                  if (errors) {
                    var message = errors == 1
                      ? 'You missed 1 field. It has been highlighted below.'
                      : errors + ' fields have not been completed. They have been highlighted below.';
                    $("h2.messageText").html(message);
                    $("h2.messageText").show();
                  } else {
                    $("h2.messageText").hide();
                  }
                }
            });
        }

        /* Contact Form Validation */
        if ($('#contactForm').length != 0) {
            $('h2.messageText').hide();
            jQuery.validator.messages.required = "";  //Defines that the error labels are populated.
            $('#contactForm').validate({
                invalidHandler: function(form, validator) {
                  var errors = validator.numberOfInvalids();
                  if (errors) {
                    var message = errors == 1
                      ? 'You missed 1 field. It has been highlighted below.'
                      : errors + ' fields have not been completed. They have been highlighted below.';
                    $("h2.messageText").html(message);
                    $("h2.messageText").show();
                  } else {
                    $("h2.messageText").hide();
                  }
                }
            });
        }

        /* Delivery address deletion via ajax */

         $( "#dialog-confirm" ).dialog({
                autoOpen: false,
                resizable: false,
                width: 350,
                height:160,
                modal: true,
                buttons: {
                    "Delete this item": function() {
                        callAjax($(this).data('url'), $(this).data('responseUrl'), $(this).data('targetDiv'));
                        $(this).dialog("close");
                    },
                    Cancel: function() {
                        $(this).dialog("close");
                    }
                }
        });

        $('.controlIcon.ajax.delete').click(function() {
           $('#dialog-confirm').data('url', $(this).attr("href"));
           $('#dialog-confirm').data('responseUrl', $(this).attr("rel"));
           $('#dialog-confirm').data('targetDiv', '.displayDiv');
           $('#dialog-confirm').dialog('open');
           return false;
        });

        /*
         * Fire the controlIcon edit function for the relevant url
         */
        $('.modalPopup').click(function() {
           modalWindow($(this).attr("href"), $(this).attr("title"), 530);
           return false;
        });

        /* View more links */
        $('.viewMoreContainer').hide();
        
        $('.viewMoreLink').click(function() {
            $('.snippetContainer').toggle();
            $('.viewMoreContainer').toggle();
            return false;
        });

        /* Enlarge image */
       $('.enlargeImage').click(function() {
           modalWindow($(this).attr('href'), $(this).attr('title'), 550);
           return false;
       });

       /* Autopopulate delivery address tickbox */
       $('#txtUseBilling').click(function() {
           if ($(this + ':checked').val() !== undefined) {
                $('#txtDeliveryTitle').val($('#txtBillingTitle').val());
                $('#txtDeliveryFirstName').val($('#txtBillingFirstName').val());
                $('#txtDeliverySurname').val($('#txtBillingSurname').val());
                $('#txtDeliveryCompany').val($('#txtBillingCompany').val());
                $('#txtDeliveryAddress').val($('#txtBillingAddress').val());
                $('#txtDeliveryAddress2').val($('#txtBillingAddress2').val());
                $('#txtDeliveryTown').val($('#txtBillingTown').val());
                $('#txtDeliveryCounty').val($('#txtBillingCounty').val());
                $('#txtDeliveryPostcode').val($('#txtBillingPostcode').val());
                $('#txtDeliveryCountry').val($('#txtBillingCountry').val());
                $('#txtDeliveryTelephone').val($('#txtBillingTelephone').val());
           } else {
                //Clear values
                $('#txtDeliveryTitle').val('');
                $('#txtDeliveryFirstName').val('');
                $('#txtDeliverySurname').val('');
                $('#txtDeliveryCompany').val('');
                $('#txtDeliveryAddress').val('');
                $('#txtDeliveryAddress2').val('');
                $('#txtDeliveryTown').val('');
                $('#txtDeliveryCounty').val('');
                $('#txtDeliveryPostcode').val('');
                $('#txtDeliveryCountry').val('');
                $('#txtDeliveryTelephone').val('');
           }
       });

       /* Enable/disable proceed button on terms checkbox toggling */
       if ($('#txtTerms').length !== 0) {
          $('#btnSubmit').attr('disabled','disabled').addClass('ui-state-disabled');
          $('#txtTerms').click(function() {
              if ($(this + ':checked').val() !== undefined) {
                  $('#btnSubmit').removeAttr('disabled').removeClass('ui-state-disabled');
              } else {
                  $('#btnSubmit').attr('disabled','disabled').addClass('ui-state-disabled');
              }
           }); 
       }
      
});

/* Contact get directions popup */
function getDirections()
{
 var postcode = document.getElementById('postcode').value;
 window.open('http://maps.google.com/maps?saddr=' + postcode + '&daddr=51.276441,0.400786','googleDirections');
}

/* Generic Functions */
function goFocus(obj)
{
	obj.focus();
}

function goDisable(obj)
{
	obj.disabled = true;
}

function goClearField(obj, text)
{
	if (obj.value == text) obj.value = '';
}

function goFillField(obj, text)
{
	if (obj.value == '') obj.value = text;
}

/*
 * Grabs the URL querystring value of the parameter passed in.
 */
function getParameterByName( name )
{
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
    return "";
    else
    return results[1];
}

/*
 *  Calls the jQuery function
 *  url - the url to be processed
 *  responseUrl - the url to be called once the initial request has been processed
 *  targetDiv - the target container the responseUrl should be loaded into.
 *
 */
function callAjax(url, responseUrl, targetDiv) {

    if (url.indexOf('?')>0) {
      url = url + "&format=ajax";
    } else {
      url = url + "?format=ajax";
    }

    $.ajax({
      url: url,
      success: function() {
          $.get(responseUrl + '?format=ajax', function(data) {
              $(targetDiv).html(data);
            });
      },
      dataType: "json"
    });
    return false;
}

/*
* Populates a jQuery UI Modal dialog from given URI, Title and width.
* Window contains additional close button and closing cross in top right.
*/
function modalWindow(url, title, width) {

    if (url.indexOf('?')>0) {
      url = url + "&format=ajax";
    } else {
      url = url + "?format=ajax";
    }
    
     $.get(url, function(data) {
        $htmlcontent = data;
        var $dialog = $('<div></div>')
            .html($htmlcontent)
            .dialog({
                    buttons: { "Close": function() { $(this).dialog("close")} },
                    autoOpen: false,
                    modal: true,
                    resizable: false,
                    width: width,
                    title: title,
					position: 'top'
            });
        $dialog.dialog('open');
        return false;
    });
    return false;
}


/* Jquery extended functions */

$.fn.extend({
	printPage: function()
	{
		$(this).click(function(e){
			window.print();
			return false;
		});
	},
	popupLinks: function() {
		$(this).live('click', function(){
			window.open($(this).attr('href'));
			return false;
		});
	},
	autoClear: function() {
		$(this).focus(function() {
			if ($(this).attr('value') == $(this).attr('alt')) {
				$(this).attr('value','');
			}
		});
		$(this).blur(function() {
			if ($(this).attr('value') == '') {
				$(this).attr('value',$(this).attr('alt'));
			}
		});
	},
	formSetup: function () {
		$(this).find('.inputField').each(function () {
			$(this).blur().focus(function () {
				$(this).addClass('focus');
				$(this).closest('li').find('label').addClass('focus');
				$(this).parent().siblings('.helper').fadeIn();
			}).blur(function () {
				$(this).removeClass('focus');
				$(this).closest('li').find('label').removeClass('focus');
				$(this).parent().siblings('.helper').fadeOut();
			});
		});
	},
        highlight: function(search, insensitive, highlight_class) {
            var regex = new RegExp("(<[^>]*>)|(\\b" + search.replace(/([-.* ?^${}()|[\]\/\\])/g,"\\$1") + ")", insensitive ? "ig" : "g");
            return this.html(this.html().replace(regex, function(a, b, c){
                return (a.charAt(0) == "<") ? a : "<strong class=\"" +  highlight_class + "\">" + c + "</strong>";
            }));
        }
});
