/* Mori Lee: Behavoural functions
 * Author: Reading Room Ltd.
 *
 */


var tmp_href_main;
var main_image_link_element;
// Check whether magnification should be applied
var magnification = false;





$(document).ready(function(){

    if( document.getElementById("thumbFeatures") ){
	$('#thumbFeatures').jshowoff({
	    cssClass: 'thumbFeatures',
	    changeSpeed:600,
	    speed:10000
	});
    }

    // Call functions
    prog_disc();
    image_swap();
    search_text();
    retailer_text();
    
    try{
	retailer_map();
    }catch(err){

    }
    $("a.fb").fancybox({
        'overlayShow'	: false
    });

    //Validate
    $(".validate").validate();
    
    // Fade in 
    $('.europe-link').hide().delay(500).slideDown(500);

    // Event track favs
    $('.fav-link a, #favs a').click(function(event){
	var page_title = $('.primary h1').html();
	track_event( 'Favorites','Add', page_title );
	window.location.href = this.href;
	event.preventDefault();
    });
    // Event track twitter shares
    $('.twitter a').click(function(event){
	track_event( 'Favorites','Share', 'Twitter' );
	window.location.href = this.href;
	event.preventDefault();
    });
    // Event track facebook shares
    $('.facebook a').click(function(event){
	track_event( 'Favorites','Share', 'Facebook' );
	window.location.href = this.href;
	event.preventDefault();
    });


    // the enlarge button is stored in where while the zoom is active, so it can be reinstated when its exited.
    var enlarge_button;
    
    var close_button_element = document.createElement("span");
    $(close_button_element).addClass('btn-close');
    
    // function for click event of enlarge button, its bound more than once so is referenced to this
    var click_function = function(){
	 // reinstate href from saved var
	 main_image_link_element[0].href = tmp_href_main;
	 $('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();
	 // apply jumping behavoiur to the little image
	 move_little_image();
	 magnification = true;
	 
	 // add close button
	 $('#wrap').append( close_button_element );
	 
	 // dont need the button any more
	 enlarge_button = $(this); // save object to reapply when zoom is exited
	 $(this).remove();
	 
	 // Track event
	 var page_title = $('.primary h1').html();
	 track_event( 'Image View','Englarge',page_title );
    }
    
    // Product detail main image
    main_image_link_element = $('.product-image .cloud-zoom');

    // Check its a detail page so this element will exist
    if( main_image_link_element.length ){

	// save the href of the enlarged image
	tmp_href_main = main_image_link_element[0].href;
	// remove href on element
	main_image_link_element[0].href = '';

	// enlarge button enables the magnifing functionality
	 $('.btn-enlarge').click(click_function).parent('a').click(function(event){
	     // prevent the a from working as a link
	     event.preventDefault();
	 });

    }
    

    
       
    // This is used to exit zoom functionality when the zoomed image is clicked.
    var remove_zoom = function(event){
	// kill cloudzoom stuff
	$('#cloud-zoom-big').remove();
	$('.mousetrap').remove();
	$(close_button_element).remove();
	// reinstate enlarge button, and bind click event
	main_image_link_element.append( enlarge_button.click(click_function) );
	
    } 
    $('.mousetrap').live( 'click', remove_zoom );
    $('.btn-close').live( 'click', remove_zoom );



    // Use browser to get the location for the store finder
    $('#findme').click(function(){
	navigator.geolocation.getCurrentPosition(
	gotPosition,
	errorGettingPosition,
	{
	    'enableHighAccuracy':true,
	    'timeout':10000,
	    'maximumAge':0
	});
	return false;
    });

    
});

// Show and hide content with the .prod-disc class
function prog_disc()
{
    $('.prog-disc .the-content').hide().siblings('h3').click(function(){
        $(this).siblings('.the-content').slideToggle().parent().toggleClass('open');
	var page_title = $('.primary h1').html();
	track_event( 'Progressive Disclosure','Show',page_title );
        return false;
    });
}



// Put text in the search box and remove it and change the colour when it needs to be used.
function search_text()
{
    if( document.getElementById("f_search") ){
	var search_advice_text = $('#f_search').siblings('label').text();

	if( $('#f_search').val().length == 0 ){
	    $('#f_search').val( search_advice_text ).css({'color':'#ccc'});
	}
	$('#f_search').focus(function(){
	    if( $(this).val().length == 0 || $(this).val() == search_advice_text ){
		$(this).val( '' ).css({'color':'#444'});
	    }
	}).blur(function(){
	    if( $(this).val().length == 0 ){
		$(this).val( search_advice_text ).css({'color':'#ccc'});
	    }
	});
    }

}

// Same as above, but a little bit different.
function retailer_text()
{
    if( document.getElementById("retailer_postcode") ){
	var retailer_text = $('#retailer_postcode').siblings('label').text();

	if( $('#retailer_postcode').val().length == 0 ){
	    $('#retailer_postcode').val( retailer_text ).css({'color':'#ccc','text-transform':'none'});
	}
	$('#retailer_postcode').focus(function(){
	    if( $(this).val().length == 0 || $(this).val() == retailer_text ){
		$(this).val( '' ).css({'color':'#444','text-transform':'uppercase'});
	    }
	}).blur(function(){
	    if( $(this).val().length == 0 ){
		$(this).val( retailer_text ).css({'color':'#ccc','text-transform':'none'});
	    }
	});
    }

}



// Declare map outside the function so it can be accessed
var map;
var markersArray = [];
var infoWindow = false;

/**
 * Initialise retailers map
 *
 */
function retailer_map()
{
    // Only run if google api is loaded
    if( typeof(google) == "undefined" || typeof(google.maps.MapTypeId) == "undefined" )
	return false;

    // create a single info window object
    infoWindow = new google.maps.InfoWindow();
    
    //Google maps defaults
    var myOptions = {
	zoom: 9,
	mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    // Create map object in map_canvas element
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    // Centre map on Latlong set by geo postion JS
    if( document.getElementById("latitude").value && document.getElementById("longitude").value ){
	var jslat = document.getElementById("latitude").value;
	var jslong = document.getElementById("longitude").value;
	
	//create new latlong object
        var centre = new google.maps.LatLng( jslat, jslong );
	map.setCenter( centre );
    }else{
    // Get searched postcode from the form to centre the map on
	var searchAddress = document.getElementById("retailer_postcode").value;

	// Geocode searched postcode and centre map there
	var geocoder = new google.maps.Geocoder();
	geocoder.geocode( {'address': searchAddress}, function(results, status) {
	    //geocoder callback function
	    if (status == google.maps.GeocoderStatus.OK) {
	       map.setCenter(results[0].geometry.location);
	    }
	});
    }


    
    // add markers when the tiles are loaded
    google.maps.event.addListenerOnce(map, 'tilesloaded', addMarkers);
    


}
/**
 * Loop through array of locations "mymarkers" returned by the store_locator class in the footer of the page
 *
 */
var addMarkers = function()
{
    try{
	if( mapdebug ){
	    var paths = [
	    new google.maps.LatLng(latbig, lngbig),
	    new google.maps.LatLng(latbig, lngsm),
	    new google.maps.LatLng(latsm, lngsm),
	    new google.maps.LatLng(latsm, lngbig)
	    ];

	    var shape = new google.maps.Polygon({
	    paths: paths,
	    strokeColor: '#ff0000',
	    strokeOpacity: 0.8,
	    strokeWeight: 2,
	    fillColor: '#ff0000',
	    fillOpacity: 0.35
	    });

	    shape.setMap(map);
	}
    }catch(e){}
    

    var createMaker = function( map, myLatLng, id, title, infoWindowString, i )
    {

	// Get numbered icons for the marker
	var markerImage
	if( i < 11 && i >= 0 ){
	    markerImage = '/wp-content/themes/morilee/images/map_marker_' + i + '.png';
	}else{
	    markerImage = '/wp-content/themes/morilee/images/map_marker_default.png';
	}

	var image = new google.maps.MarkerImage(
	  markerImage,
	  new google.maps.Size(36,36),
	  new google.maps.Point(0,0),
	  new google.maps.Point(5,36)
	);

	var shadow = new google.maps.MarkerImage(
	  '/wp-content/themes/morilee/images/map_marker_shad.png',
	  new google.maps.Size(58,36),
	  new google.maps.Point(0,0),
	  new google.maps.Point(5,36)
	);

	var shape = {
	  coord: [17,0,19,1,20,2,21,3,21,4,22,5,22,6,23,7,23,8,23,9,23,10,23,11,23,12,23,13,23,14,23,15,23,16,22,17,22,18,21,19,21,20,20,21,19,22,17,23,14,24,11,25,10,26,9,27,8,28,8,29,7,30,7,31,7,32,7,33,7,34,6,35,3,35,3,34,3,33,2,32,2,31,2,30,2,29,2,28,2,27,1,26,1,25,1,24,1,23,1,22,0,21,0,20,0,19,0,18,0,17,0,16,0,15,0,14,0,13,0,12,0,11,0,10,0,9,0,8,0,7,0,6,0,5,1,4,1,3,2,2,4,1,5,0,17,0],
	  type: 'poly'
	};


	// Create marker object for the retailer
	var marker = new google.maps.Marker({
	    position: myLatLng,
	    map: map,
	    title: title,
	    id: id,
	    icon:image,
	    shadow:shadow,
	    shape:shape
	});

	// Store marker objects in an array to manipulate them later
	markersArray[id] = marker;

	// Bind listener to markers click event
	google.maps.event.addListener(marker, 'click', function() {
	    // Change Content
	    infoWindow.setContent( infoWindowString );
	    infoWindow.open(map,this);
	});

	// Hover events for effects on list items
	google.maps.event.addListener(marker, 'mouseout', function(){
	    $( '.retailer-listing li' ).removeClass('marker-hover');
	});

	google.maps.event.addListener(marker, 'mouseover', function(){
	    $( '#retailer_id_' + this.id ).addClass('marker-hover');
	});
    }// /createMarker ----------------------------------------------------------
    
    // Loop
    for (var i = 0; i < mymarkers.length; i++) {
	retailerLocation = mymarkers[i]; // curent item

	// create a latlong object for the marker
	var myLatLng = new google.maps.LatLng(retailerLocation.lat, retailerLocation.lng);

	// Build infoWindow string
	var infoWindowString = '<h3>' + retailerLocation.name + '</h3>' + '<p>' + retailerLocation.address1 + '<br />' + retailerLocation.address2 + '<br />' + retailerLocation.address3 + '<br />' + retailerLocation.postcode + '<p>';

	// Create and register maker
	createMaker( map, myLatLng, retailerLocation.id, retailerLocation.name, infoWindowString, i );
	
    }// /loop

}// /addMarkers ----------------------------------------------------------------





var move_little_image = function()
{
    // Flag to indicate state of image position
    var displaced = false;

    // Check if the thing is zoomed or not
    setInterval(function(){
	// Image is zoomed if the element exists
	if( !document.getElementById('cloud-zoom-big') ){
	    if( displaced == true ){
		$('.product-image .sub').animate({
		    left: ['-80', 'easeOutBounce']
		},700);
		displaced = false;
	    }
	}else{
	    if( displaced == false ){
		$('.product-image .sub').animate({
		    left: ['-220', 'easeOutBounce']
		},700);
		displaced = true;
	    }
	}
    },100);
}



// Swap front and back images on product pages via image references from a json object in the footer.
function image_swap()
{
    var main_image = $('.product-image .main img');
    var sub_image = $('.product-image .sub img');
    var enlarged_main_image = $('.product-image .cloud-zoom');

    var toggle = 0;

    $('a.toggle-fb').click(function(){

	// toggle == 0 means front is showing
	// toggle == 1 means back is showing

	if( toggle == 0 ){
            main_image[0].src = images[3].src; // main image show large back image
            sub_image[0].src = images[0].src; // small image show small front image

	    if( true == magnification ){
		enlarged_main_image[0].href = images[5].src; //back zoom
		tmp_href_main = images[5].src;
	    }else{
		// Enlarge is not yet enabled so save href in this var
		tmp_href_main = images[5].src;
	    }

            toggle = 1;
        }else if( toggle == 1 ){
            main_image[0].src = images[1].src; // main image show large front image
            sub_image[0].src = images[2].src; // small image show small back image
	    
	    if( true == magnification ){
		enlarged_main_image[0].href = images[4].src; //back zoom
		tmp_href_main = images[5].src;
	    }else{
		// Enlarge is not yet enabled so save href in this var
		tmp_href_main = images[4].src;
	    }

            toggle = 0;

        }

	var page_title = $('.primary h1').html();
	track_event( 'Image View','Toggle View',page_title );

	// Check whether to re-bind cloudzoom
	if( true == magnification ){
	    $('.cloud-zoom, .cloud-zoom-gallery').CloudZoom(); // call this again so it checks the src in the .cloud-zoom href
	}
	
    });




}

//Special call back function
var k = [], xrayvision = "88,82,65,89,86,73,83,73,79,78", konami = "38,38,40,40,37,39,37,39,66,65";;
jQuery(document).keydown(function(e) {
  
    k.push( e.keyCode );
 
    if ( k.toString().indexOf( konami ) >= 0 || k.toString().indexOf( xrayvision ) >= 0 ){
	move_little_image();
	magnification = true;
	var enlarged_main_image = $('.product-image .cloud-zoom');
	enlarged_main_image[0].href = '/wp-content/themes/morilee/images/skel.jpg'; //back zoom
	$('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();
	k = [];
    }
});


var track_event = function(category, action, optional_label){
    try {
	if( 'object' == typeof( _gaq ) ){
	    _gaq.push(['_trackEvent', category, action, optional_label]);
	}
    } catch(err){}
}









// Callback functions for geo lookup
// Error handler for geo lookup
function errorGettingPosition(err)
{
    if(err.code==1){
	alert("User denied geolocation.");
    }else if(err.code==2){
	alert("Position unavailable.");
    }else if(err.code==3){
	alert("Timeout expired.");
    }else{
	alert("ERROR:"+ err.message);
    }
}

// callback for successful geolocation
function gotPosition(pos)
{
    track_event( 'Geo Lookup', 'Got Position' );

    $('#latitude').val(pos.coords.latitude);
    $('#longitude').val(pos.coords.longitude);

    document.forms['retailerSearchForm'].submit();
}




