// Common JavaScript code across your application goes here.

// for showing different sections, initially for 'Us' page.. 
// assumes div class of 'page-section'
function show_section( id ) {
	$('div.page-section').hide();
        if( $(id) ) {
	  $(id).show();
	  $('a.hash.selected').removeClass('selected');
  	  $(id+'_hash').addClass('selected');
          return false;
        } 
        	
	//window.location.hash = id;
}

/*
 * JQuery Random Plugin
 * 
 * Adds two random number functions to jQuery -
 * one to find a random number and one to find a random number between a max and min limit.
 * 
 * Version 1.0
 * 
 * by Christian Bruun - 23. jan 2009
 * 
 * Like it/use it? Send me an e-mail: rockechris@rockechris.com
 * 
 * License: None. Use and abuse. Comes with no warranty, of course!
 * 
 * 
 * Usage:
 * $.random(int);
 * $.randomBetween(min, max);
 * 
 * Code found at:
 * http://www.merlyn.demon.co.uk/js-randm.htm
 * 
 */
jQuery.extend({
  random: function(X) {
      return Math.floor(X * (Math.random() % 1));
  },
  randomBetween: function(MinV, MaxV) {
    return MinV + jQuery.random(MaxV - MinV + 1);
  }
});


$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});


// JS specific to a single component i.e. the Slideshow or Google Maps should be added to its own JS file and included by relevant partial
$(document).ready(function() {
	
	// IE transparent PNG fix
	//$('#outline').supersleight({shim: '/images/transparent.gif'});
  //$('#nav').supersleight({shim: '/images/transparent.gif'});

  // Client-side relative timestamps using timeago plugin: http://timeago.yarp.com/
  // Timestamps update dynamically on client-side as time passes plus is also helpful for caching as generated output doesn't have to change between requests
  $('abbr[class*=timeago]').timeago();

  // Smooth scroll internal page anchors using scrollTo plugin http://bit.ly/v35o and localScroll plugin http://bit.ly/lgXb
  //$.localScroll(); // TODO: Increase scrolling speed - james.
	
	$('a#tell').fancybox({
		'padding': 1,
		'hideOnContentClick': false
	});
	
	$('a#subscribe').fancybox({
    'padding': 1,
		'frameWidth': 580,
		'frameHeight': 420,
		'hideOnContentClick': false,
		'callbackOnShow': setupSubForm
  });

  // highlight hash sub-section headings
  var hash = location.hash;
  if( hash.length > 0 ) {
    var hash_element = $(hash+'_hash');
    if( hash_element ) {
      hash_element.addClass('selected');
    }
  } 

  // Home page Our Services dynamic reveals
  $('#intro .services ul li a').click(function() {
    // Set selected state
    $(this).parents('ul').find('a').removeClass('selected');
    $(this).addClass('selected');
    // Reveal copy
    var service = $(this).parent()[0].id;
    $(this).parents('.services').children('div').hide().end().children('div.' + service).fadeIn();
    return false;
  });
  
  // In-field-automagically-disapearing form labels
  $('form input[type=text]').placeholder();
  
  // Home page Vacancies form
  if ($('#vacancies .vacancy').length > 1) {
    $('#vacancies .vacancy:gt(0)').hide();
    var select_for_vacancies = function(vacancies) {
      options = [];
      vacancies.each(function(index) {
        id       = this.id;
        position = $(this).children('h4')[0].innerHTML;
        options += '<option value="' + id + '">' + position + '</option>';
      });
      return $('<select>' + options + '</select>').change(function() {
        vacancies.hide().filter('#' + this.value).fadeIn();
      });
    }
    // Following is a litle bit ug, could do with some .wrap()ing - james
    $('#vacancies').prepend('<form id="vacancy_selector"></form>').children('form#vacancy_selector').prepend(select_for_vacancies($('#vacancies .vacancy')));
    // Set min-height on #vacancies to alleviate nasty page jump on vacancy selection
    $('#vacancies').css('min-height', $('#vacancies').css('height'));
  };

  // Scrolling image slideshows
  if ($('#slideshow').length > 0 && !($.browser.msie && $.browser.version == '6.0')) {
    $('#slideshow').children('#slides img, .paging').show();
    $('#slideshow #slides').cycle({ 
      fx:     'scrollHorz', 
      speed:  500, 
      timeout: 0, 
			height: 445,
      next:   '#slideshow .paging .next', 
      prev:   '#slideshow .paging .prev',
      before:  onBeforeSlide, 
      after:   onAfterSlide 			
    });
  }
	
	
	// Check for 'Us' page - show/hide sections
	if ($('#what_is_it').length > 0 ) {
		
		if (window.location.hash != ''  ) {

      show_section(window.location.hash);
		}
		else {
			
			show_section('#what_is_it');
		}
		
	}

	
  if ($('#online-marketing').length > 0 ) {
    if (window.location.hash != ''  ) {
      show_section(window.location.hash);
    }
    else {    
      show_section('#channels');
    }
  }	

/*  
  if ($('#company-websites').length > 0 ) {
    if (window.location.hash != ''  ) {
      show_section(window.location.hash);
    }
    else {    
      show_section('#company-websites');
    }
  } 	
*/


  // jMaps jQuery plugin code & documentation available at: 
  // http://code.google.com/p/jmaps/
  // http://map.ifies.org/
  if ($('#map').length > 0) {
    // Using hard-coded geo data in vcard as address search doesn't want to return half-accurate results - james.
    var vcard = $('.vcard#liveline_london')
    var office = {
      'org':      vcard.find('a.org').html(),
      'street':   vcard.find('.street-address').html(),
      'locality': vcard.find('.locality').html(),
      'postcode': vcard.find('.postal-code').html(),
      'country':  vcard.find('.country-name').html(),
      'geo':      [parseFloat(vcard.find('.geo .latitude').html()), parseFloat(vcard.find('.longitude').html())]
    }
    office.toHtml = function() {
      return '<b>' + this.org + '</b><br/>' + this.street + '<br/>' + this.locality + '<br/>' + this.postcode + '<br/>' + this.country;
    };

    $('#map').jmap(
      'init', {
        'mapType':                  'map', // N.B. mapType param as a string deprecation warning: http://bit.ly/4kFoQm
        'mapZoom':                  12,
        'mapControl':               'large',
        'mapEnableType':            true,
        'mapEnableInfoWindows':     true,
        'mapEnableDoubleClickZoom': true,
        'mapEnableSmoothZoom':      true,
        'mapEnableScaleControl':    true,
        'mapShowjMapsIcon':         false
      }).jmap(
      'AddMarker', {
    		'pointLatLng': office.geo,
    		'pointHTML':   office.toHtml(),
    		'centerMap':   true
  	  });
			// API key=ABQIAAAA4OxpdRrS-uzIqcVZh8ml7xRp2nr3FxvRbgfdGtawngKlVfn2uhRKhLM3DpEfvlfoVwzeNM-0yDcg0Q
  };
	
	
  //setupSubForm();
	
});


function setupSubForm() {
	
  $("#submit-subscribe").click(function(){   
	  //alert('sub form!!!');                    
    $(".error").hide();
    var hasError = false;
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    
    var emailVal = $("#email").val();
    if(emailVal == '') {
      $("#email").after('<span class="error">Please enter a valid email address.</span>');
      hasError = true;
    } else if(!emailReg.test(emailVal)) { 
      $("#email").after('<span class="error">Please enter a valid email address.</span>');
      hasError = true;
    }
 
    var firstnameVal = $("#first_name").val();
    if(firstnameVal == '') {
      $("#first_name").after('<span class="error">Please enter your first name.</span>');
      hasError = true;
    }
    
    var surnameVal = $("#surname").val();
    if(surnameVal == '') {
      $("#surname").after('<span class="error">Please enter your last name.</span>');
      hasError = true;
    }
    
    var companyVal = $("#company").val();
    var phoneVal = $("#phone").val();
    var cidVal = '4625';
    var hashVal = '03fe3345db61b6a3f5b1814238249baa';
    var pidVal = '45005';
    var mode = 'add';
    
    if(hasError == false) {
      
      $("#submit-subscribe").hide();
      $("#loading").show();
      //alert('about to call $.get');

			// ?cid=4625&hash=03fe3345db61b6a3f5b1814238249baa&pid=45005&mode=add",
			
      $.get("http://api.sign-up.to/capture.php", 
          { 
            email: emailVal, 
            first_name: firstnameVal, 
            surname: surnameVal, 
            phone: phoneVal, 
            company: companyVal,
						cid: cidVal,
						hash: hashVal,
						pid: pidVal,
						mode: 'add'
          },
            function(data){
							//alert('sent!! :'+data );
							/*
              $("#subscription-form").slideUp("normal", function() {           
              
                $("#subscription-form").before('<h1>Success</h1><p>Your subscription was sent.</p>');                      
              });
            */
            }, "text"
         );
				 //alert('sent?????? or what');
				 
            $("#subscription-form").slideUp("normal", function() {           
              
              $("#subscription-form").before('<h1>Success</h1><p>Your subscription was sent.</p>');                      
            });
							
							
				    $("#loading").hide();				 
				 
    }
    
    return false;
  });   	
}



function onBeforeSlide() { 
   // $('#slideshow').html("Scrolling image:<br>" + this.src);

} 

var santa = false;

function onAfterSlide() { 
   // $('#slideshow').html("Scroll complete for:<br>" + this.src) 
   //     .append('<h3>' + this.alt + '</h3>'); 
	 
/*
	 if (santa) {
   	 if ($.random(9) > 5) {

   		 $('#slideshow').load( "/santa-form #santa-form" );
			 alert('Congratulations! You won a prize!');
			 //if( $('#prize_span').html() == '...') { $('#prize_span').load( '/pick_a_prize' ); }
			 
			 setTimeout( "if( $('#prize_span').html() == '...') { $('#prize_span').load( '/pick_a_prize' ); }", 200 );

			 //alert('Now enter your details...');
			 
			 $('#prize_name').val( $('#prize_span').html());
			 
			 //setTimeout( "if( $('#prize_name').html() == 'Sorry! All prizes now taken!' ) { $('santa-form').hide(); }", 3500 );
			 
  		 setTimeout( "$('#prize_name').val( $('#prize_span').html()); ", 3000 );
   	 }
   } else santa = true;
*/  	 
}
