var main = new Object();
var original_prices = new Object();

$(function(){	  		   
	var ie = (function(){
		var undef,
			v = 3,
			div = document.createElement('div'),
			all = div.getElementsByTagName('i');
		
		while (
			div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
			all[0]
		);
		
		return v > 4 ? v : undef;
	}()), timeout;
	
	$.fn.removeClasses = function(a){
		for(var i=0; i<a.length; i++){
			if(a[i].length > 0){
				this.removeClass(a[i]);
			}
		}
		
		return this;
	}
	
	$.fn.quickEach = (function() {
		var jq = jQuery([1]);
		
		return function(c) {
			var i = -1,
				el, len = this.length;
			try {
				while (++i < len && (el = jq[0] = this[i]) && c.call(jq, i, el) !== false);
			} catch (e) {
				delete jq[0];
				throw e;
			}
			
			delete jq[0];
			return this;
		};
	}());
	
	$.cookie = function (key, value, options) {
		if (arguments.length > 1 && String(value) !== "[object Object]") {
			options = jQuery.extend({}, options);
	
			if (value === null || value === undefined) {
				options.expires = -1;
			}
	
			if (typeof options.expires === 'number') {
				var days = options.expires, t = options.expires = new Date();
				t.setDate(t.getDate() + days);
			}
			
			value = String(value);
			
			return (document.cookie = [
				encodeURIComponent(key), '=',
				options.raw ? value : encodeURIComponent(value),
				options.expires ? '; expires=' + options.expires.toUTCString() : '', 
				options.path ? '; path=' + options.path : '',
				options.domain ? '; domain=' + options.domain : '',
				options.secure ? '; secure' : ''
			].join(''));
		}
	
		options = value || {};
		var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
		return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
	};
	
	function addCommas(nStr){
		nStr += '';
		x = nStr.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
		return x1 + x2;
	}
		
	var curr_currency = $.cookie('wf_currency');

	if(!curr_currency){
		curr_currency = 'GBP';
		$.cookie('wf_currency', 'GBP', {path: '/'});
	}

	if($('span.price').length > 0 || $('span.symbol').length > 0){
		var html = '<span class="arrow"></span>'+curr_currency;
		$('.currency').find('.selected').html(html);
		api('wild_frontiers', '_model', 'get_exchange_rate', [curr_currency], function(rate){
			exchange_rate = rate.exchange_rate;
			
			$('span.symbol').quickEach(function(){
				this.html(rate.symbol)
			})

			$('span.price').quickEach(function(){

				var new_price = parseInt(this.attr('rel')) * parseFloat(exchange_rate);
				this.html(addCommas(Math.ceil(new_price)));

			})
			
		})
	}
	
	if($('#wild_carousel .carousel_slides').length){
		$('#wild_carousel .carousel_slides').cycle({ 
			speed:  1, 
			timeout: 5000,  
			pager:  '.carousel_nav ul', 
			cleartype: 1,
			pause: true,
			fastOnEvent: 500,
			after: function(curr, next, opt, fwd){
				var eq = $(next).index(),
					arr = new Array('first', 'second', 'third', 'forth', 'fifth'),
					href = $(next).find('a').attr('href');
							
				$('.carousel_nav').removeClasses(arr).addClass(arr[eq]);
				$('#view_link').attr('href', href);
			},
			pagerAnchorBuilder: function(idx, slide) { 
				return ".carousel_nav ul li:eq("+idx+") a";
			} 
		});
	}
	
	$('#label_crm_field_68').parent().css({
		clear: 'left'
	})
	
	$('.crm_form h3').parent().css({
		width: 400
	})
		
	$('.currency li a').live('click', function(){
		var t = $(this),
			code = t.text(),
			html = '<span class="arrow"></span>'+code;
			
		$('.currency').find('.selected').html(html);
			
		api('wild_frontiers', '_model', 'get_exchange_rate', [code], function(rate){
			$.cookie('wf_currency', rate.currency_code, {path: '/'});
			$('span.symbol').quickEach(function(){
				this.html(rate.symbol)
			})
			
			$('span.price').quickEach(function(){
				var new_price = parseInt(this.attr('rel')) * parseFloat(rate.exchange_rate);
				this.html(addCommas(Math.ceil(new_price)));
			});
		})
	})
	
	$('#faux_search_form button.open').click(function(){
		var t = $(this),
			id = t.attr('id'),
			sel = '#'+id+'_open';
			
		if($(sel).is(':visible')){
			$('#search_form fieldset').removeClass('open');
			$(sel).hide();
			t.removeClass('close').addClass('open');
		}
		else {
			t.parent().parent().removeClass('open');
			$('#search_form button.close').removeClass('close').addClass('open');
			$('.advanced_search').hide();
			$(sel).show();
			t.removeClass('open').addClass('close');
			setTimeout(function(){
				$(sel).find('button').show();
			}, 1000)
		}
		
		return false;
	})
		
	if($('#crm_fieldset_id_12 div input:checked').val() == 'Download'){
		$('#crm_field_39, #crm_field_40, #crm_field_41, #crm_field_42, #crm_field_43, #crm_field_44, #crm_field_45, #crm_field_47').parent().hide();
	}
	
	$('#crm_fieldset_id_12 div input').live('change', function(){
		if($(this).val() == 'Download'){
			$('#crm_field_39, #crm_field_40, #crm_field_41, #crm_field_42, #crm_field_43, #crm_field_44, #crm_field_45, #crm_field_47').parent().hide();
		}
		else {
			$('#crm_field_39, #crm_field_40, #crm_field_41, #crm_field_42, #crm_field_43, #crm_field_44, #crm_field_45, #crm_field_47').parent().show();
		}
	})
	
	$('#log_in_form').live('submit', function(e){
		e.preventDefault();
		
		var t = $(this),
			email = t.find('[name="email"]'),
			password = t.find('[name="password"]');
			
			$('#login_loader').show();
			
		api('wild_frontiers_auth', '_model', 'login', [email.val(), password.val()], function(response){
			email.removeClass('error');
			password.removeClass('error');
			$('#error_warning').remove();
			
			if(response['errors']){
				$('#login_loader').hide();
				t.before('<p id="error_warning" style="color: red;">Please correct the errors indicated below.</p>');
				
				if(typeof(response['errors']['email']) != 'undefined'){
					email.addClass('error');
				}
				
				if(typeof(response['errors']['password']) != 'undefined'){
					password.addClass('error');
				}
			}
			else if(response['login_error']){	
				$('#login_loader').hide();
				t.before('<p id="error_warning" style="color: red;">Incorrect email / password</p>');
			}
			else {
				var id = t.find('[name="departure"]').val();
				api('wild_frontiers', '_view', 'render_dossier_download_logged_in', [id], function(html){
					$('#dossier_download').css('width', 400).html(html);
					$.colorbox.resize({width: 500, height: 210});
				})
				
			}
		})
	})
	
	$('#holiday_type').change(function(){
		if(this.value == 'tailor-made'){
			$('#wild_world, #month, #price').val('').css('color', '#A7A6AA').focus(function(){
				$(this).blur();
			})
		}
		else {
			$('#wild_world, #month, #price').css('color', '#000000').unbind('focus');
		}
	})
	
	if(ie == 7){
		
	}
	
	if(typeof($.colorbox) != 'undefined'){
		$('.colorbox, a[rel=photo_gallery]').colorbox({
			initialWidth: 10,
			initialHeight: 10,
			onOpen: function(){
				$('.video').hide();
			},
			onClosed: function(){
				$('.video').show();
			}
		});
	}
})
