function resize() {
	var height = $('#container').height() > $(window).height() ? $('#container').height() : $(window).height();
	var top = height - $('#extra_div1').height();
	$('#extra_div1').css('top', top);
}

function openCalculator() {
	if (!move && $('#pricing_box1 h2').parent().hasClass('closed')) {
		$('#pricing_box1 h2').click();
	}
}

function updateValues() {
	var period = $('input[name="radio1"]:checked').val();
	
	var ind1 = (100-slider_values[0])+"%-"+slider_values[0]+"%";
	$('#indicator1 strong').text(ind1);

	var ind2 = (100-slider_values[1])+"%-"+slider_values[1]+"%";
	$('#indicator2 strong').text(ind2);
	
	var ind3 = (100-slider_values[2])+"%-"+slider_values[2]+"%";
	$('#indicator3 strong').text(ind3);
	
	var val4 = Math.floor(1.5*slider_values[3]);
	if (period == 'day') val4 = Math.floor(val4/30);
	var ind4 = val4+" min";
	if (slider_values[3] == 100) ind4 += '+';
	$('#indicator4 strong').text(ind4);
	
	var val5 = Math.floor(1.5*slider_values[4]);
	if (period == 'day') val5 = Math.floor(val5/30);
	var ind5 = val5+" sms";
	if (slider_values[4] == 100) ind5 += '+';
	$('#indicator5 strong').text(ind5);
	
	var ind6 = Math.floor(1.5*slider_values[5])+" min";
	if (slider_values[5] == 100) ind6 += '+';
	$('#indicator6 strong').text(ind6);
	
	var ind7 = Math.floor(1.5*slider_values[6])+" min";
	if (slider_values[6] == 100) ind7 += '+';
	$('#indicator7 strong').text(ind7);
}

function unselectOffer() {
	$('#moving_arrow').css('visibility','hidden');
	$('#moving_offer').hide();
}

function selectOffer(n) {
	if (n < 4) {
		if (!move) {
			move = true;
			
			$('#moving_arrow').css('visibility','visible');
			$('#moving_offer').show();
			
			var nval = (n-1)*310;

			$('#moving_arrow').animate({
				left: nval+133
			}, 500, 'swing', function() {
				move = false;
			});

			$('#moving_offer').animate({
				left: nval
			}, 350, 'swing', function() {
				move = false;
			});
		}
	}
	else {
		unselectOffer();
	}
	
	var offer;
	
	switch (n) {
		case 1 : offer = '42€ NoLimit WiFi'; break;
		case 2 : offer = '26€ NoLimit Evening+WE'; break;
		case 3 : offer = '14€ NoLimit WiFi Fix'; break;
		case 4 : offer = '<a href="http://www.mondialtelecom.be/PRODUITS/MTMOBILE/tabid/61/language/en-US/Default.aspx" target="_blank">MTMobile</a>'; break;
	}
	
	$('#youshould_subscription strong').html(offer);

}

function selectUpgrade(n) {
	$('th.selected').removeClass('selected');
	$('td.selected').removeClass('selected');
	
	$('th.upgrade'+n).addClass('selected');
	$('td.upgrade'+n).addClass('selected');
}

function calculate() {
	var calls = 1.5*slider_values[3];
	var sms = slider_values[4];
	
	if (slider_values[0] >= 85) {
		selectOffer(4);
	}
	else {
		if (calls*((100-slider_values[2])/100)*0.22 <= 10) {
			selectOffer(3);
		}
		else {
			if (slider_values[2] >= 70) {
				selectOffer(3);
			}
			else {
				if (slider_values[1] >= 70) {
					selectOffer(2);
				}
				else {
					selectOffer(1);
				}
			}
		}
	}
	
	// free WiFi
	
	if ($('input[name="radio2"]:checked').val() == "yes") {
		$('#free_wifi').show();
	}
	else {
		$('#free_wifi').hide();
	}
	
	// international pack
	
	$('#youshould_subscription span').remove();
	if (slider_values[5] >= 25) {
		$('#youshould_subscription').html($('#youshould_subscription').html()+'<span> + international pack</span>')
	}
	
	$('#pricing_box1 h2 span').html($('#youshould_subscription').html());
	
}

function resetLabel() {
	$('#question'+k+' .label').text(old_question_label);
	$('#question'+k+' .label').css('color','#CA1F50');
	move = false;
}

var device_num = 0;

function updateDevices() {
	var excluded = new Array();
	$('.device').each(function() {
		excluded.push($(this).attr('id').substring(1));
	});
	$.getJSON("/devices.php?excluded="+excluded.join('-'), function(data){
		var current = $('.device').eq(device_num);
		current.fadeOut(500, function() {
			$(this).attr('id','d'+data.id);
			$(this).find('img').attr('src','/_img/gsm/'+data.picture);
			$(this).find('strong').text(data.name);
			$(this).fadeIn(500);
		});
		device_num = (device_num+1)%4;
	});
}

var home_TwitterSshow={};
home_TwitterSshow.run=function(){
	var _this = home_TwitterSshow;
	if(_this.index>-1){
		$(_this.items[_this.index]).fadeOut(500,function(){
			_this.index++;
			if(_this.index>=_this.items.length)_this.index=0;
			$(_this.items[_this.index]).fadeIn(500);
		});
	}else{
		_this.index++;
		if(_this.index>=_this.items.length)_this.index=0;
		$(_this.items[_this.index]).fadeIn(500);
	}
	setTimeout(_this.run,4000);
}
home_TwitterSshow.init=function(){
	this.index=-1;
	this.items=$('#news .tweet-status');
	this.run();
}

var home_PartnersSshow={};
home_PartnersSshow.run=function(){
	var _this = home_PartnersSshow;
	if(_this.index>-1){
		$(_this.items[_this.index]).fadeOut(800);
	}
	_this.index++;
	if(_this.index>=_this.items.length)_this.index=0;
	$(_this.items[_this.index]).fadeIn(800);

	setTimeout(_this.run,3000);
}
home_PartnersSshow.init=function(){
	this.index=-1;
	this.items=$('#home_partners .partner');
	this.run();
}

var move = false;
var nb_sliders = 7;
var slider_values = new Array(nb_sliders);
var slider_default = new Array(25, 25, 25, 75, 75, 0, 0);

for (var i=0; i<nb_sliders; i++) {
	slider_values[i] = slider_default[i];
}

var default_subtitle;
var old_question_label;
var k;

$(document).ready(function() {
	
	$('#container').after('<div id="extra_div1"></div>');
	
	if ($('body').attr('id') == 'home') {
		
		$('#home_flash').css('background', 'transparent none');
		
		/* banner Nokia E63
		$('#home_flash').flash({
			swf: '/_swf/cherry_bannerHome.swf',
			width: 930,
			height: 287,
			flashvars : {
				lg: $('body').attr('class'),
				targetURL: 'http://www.becherry.be/'+$('body').attr('class')+'/promoE63'
			}
		});
		*/

		$('#home_flash').flash({
			swf: '/_swf/3reasons.swf',
			width: 930,
			height: 287,
			flashvars : {
				lg: $('body').attr('class')
			}
		});
		
		home_TwitterSshow.init();
		home_PartnersSshow.init();
		
	}
	
	if ($('body').attr('id') == 'how') {
		
		$('#how_flash').css('background', 'transparent none');
		
		$('#how_flash').flash({
			swf: '/_swf/mainContainer.swf',
			width: 920,
			height: 304,
			wmode: 'transparent',
			base: '/_swf/',
			flashvars : {
				lg: $('body').attr('class')
			}
		});
	
	}
	
	//----------> WHY
	if ($('body').attr('id') == 'why') {
		
		$('#why_flash').css('background', 'transparent none');
		
		$('#why_flash').flash({
			swf: '/_swf/videoPlayer.swf',
			width: 800,
			height: 334,
			flashvars : {
				lg: $('body').attr('class')
			}
		});
	}
	
	//----------> HOME
	
	if ($('body').attr('id') == 'home') {
		
		$('form')[0].reset();
		
		var input_val = $('#newsletter .text').val();
		
		$('#newsletter .text').focus(function() {
			if ($(this).val() == input_val) {
				$(this).val('');
			}
		});
		
		$('#newsletter .text').blur(function() {
			if ($(this).val() == '') {
				$(this).val(input_val);
			}
		});
		
	}
	
	//----------> STORES
	
	var map, icon, icon2, s_point, s_marker;
	
	function zoom() {
		if (s_marker) {
			map.removeOverlay(s_marker);
		}
		if ($('#stores_search input').val() == '') {
			$('#stores_search input').css('borderColor','#DA194F');
		}
		else {
			$('#stores_search input').css('borderColor','#D5D5D5');
			$.getJSON("/search.php", {location: $('#stores_search input').val()}, function(data){
				var min = Number.MAX_VALUE;
				var closest;
				for (var i=0; i<data.results.length; i++) {
					if (data.results[i].distance < min) {
						min = data.results[i].distance;
						closest = data.results[i];
					}
				}
				s_point = new GLatLng(data.search[0], data.search[1]);
				s_marker = new GMarker(s_point, icon2);
				map.addOverlay(s_marker);
				
				var bounds = new GLatLngBounds();
				bounds.extend(new GLatLng(closest.x, closest.y));
				bounds.extend(s_point);

				map.setZoom(map.getBoundsZoomLevel(bounds)-1);
				map.setCenter(bounds.getCenter());
			});
		}
	}
	
	if ($('body').attr('id') == 'stores') {
		map = new GMap2(document.getElementById('map'));
		map.setCenter(new GLatLng(50.8, 4.6735162), 8);
		map.setUIToDefault();
		map.setMapType(G_PHYSICAL_MAP);
		
		icon = new GIcon();
		icon.image = "/_img/icon.png";
		icon.iconSize = new GSize(26, 35);
		icon.iconAnchor = new GPoint(9, 28);
		
		icon2 = new GIcon();
		icon2.image = "/_img/icon2.png";
		icon2.iconSize = new GSize(26, 35);
		icon2.iconAnchor = new GPoint(9, 28);
		
		var path = (window.location.search == '?l') ? "/get.php?filter=l" : "/get.php";
		
		$.getJSON(path,function(data){
			$.each(data,function(i, n) {
				var point = new GLatLng(n.x, n.y);
				var marker = new GMarker(point, icon);
				map.addOverlay(marker);
				GEvent.addListener(marker,"click", function() {
					var html = '<div class="store_illu"><img src="/_img/cerise.jpg" width="54" height="65" /></div><div class="store_item"><strong class="store_name">'+n.name+'</strong><br /><span class="store_address">'+n.address+'<br />'+n.locality+' '+n.zip;
					if (n.phone != '') html += '<br /><strong>T</strong>: '+n.phone;
					if (n.fax != '') html += '<br /><strong>F</strong>: '+n.fax;
					html += '</span></div>';
					map.openInfoWindowHtml(marker.getLatLng(), html, {pixelOffset: new GSize(0,-26)});
				});
			});
		});
		
		$('#stores_search .button').click(function() {
			zoom();
			return false;
		});
		
		$('#stores_search input').keypress(function(e) {
			if (e.which===13) {
				zoom();
			}
		});
		
	}
	
	//----------> CALCULATOR
	
	if ($('body').attr('id') == 'howmuch') {
		
		default_subtitle = $('#pricing_box1 h2 span').html();
		
		unselectOffer();
		updateValues();
		setTimeout('openCalculator()', 500);
		
		$('.pricing_box #calculator_more .more').css('height',$('.pricing_box #calculator_more .more').height());
		
		$('#upgrades').parent().css({
			height: $('#upgrades').height(),
			borderTop: '1px solid #adadad'
		});

		$('.collapsable .closed .more').css('display','none');

		$('#youshould').css('display','none');

		$('.collapsable h2').css('cursor','pointer').click(function() {
			if (!move) {
				move = true;
				var state = $(this).parent().attr('class');
				if (state == 'closed') {
					$(this).next().slideDown(500, function() {
						move = false;
						resize();
					});
					$(this).parent().removeClass('closed').addClass('open');

					if ($(this).parent().parent().attr('id') == 'pricing_box1') {
						$('#youshould').slideDown(500);
						$(this).parent().parent().animate({
							marginBottom: 0
						}, 500);
						$('#pricing_box2 h2').slideUp(500);
						$('#pricing_box2 .more').slideDown(500);
						$('#pricing_box2').css('border-top', '0');
						setTimeout('calculate()', 750);
					}

				}
				else {
					$(this).next().slideUp(500, function() {
						move = false;
						resize();
					});
					$(this).parent().removeClass('open').addClass('closed');

					if ($(this).parent().parent().attr('id') == 'pricing_box1') {
						$('#youshould').slideUp(500);
						$(this).parent().parent().animate({
							marginBottom: 40
						}, 500);
						$('#pricing_box2 h2').slideDown(500);
						$('#pricing_box2 h2').parent().removeClass('closed').addClass('open');
						$('#pricing_box2').css('border-top', '2px solid #e2e0e1');
						unselectOffer();
						$('#pricing_box1 h2 span').html(default_subtitle);
					}

				}
			}
		});
		
		$('#pricing_box4 h2').css('cursor','pointer').click(function() {
			var href = $(this).find('a').attr('href');
			window.open(href,'_blank');
		});
		$('#pricing_box4 h2 a').click(function() {
			var href = $(this).attr('href');
			window.open(href,'_blank');
			return false;
		});
		
		for (var i=1; i<=nb_sliders; i++) {
			$("#slider"+i).slider({
				animate: true,
				value: slider_default[i-1],
				slide: function(event, ui) {
					var j = parseInt($(this).attr('id').substr(6))-1;
					slider_values[j] = ui.value;
					updateValues();
				},
				change: function(event, ui) {
					if (!move) {
						k = parseInt($(this).attr('id').substr(6)-1);
						if (k == 6) {
							move = true;
							old_question_label = $('#question'+k+' .label').text();
							$('#question'+k+' .label').text($('#same_price_wifi').text());
							$('#question'+k+' .label').css('color','#309DCC');
							setTimeout('resetLabel()', 3000);
						}
					}
					calculate();
				}
			});
		}

		$('#calculator_more .intro').css('cursor','pointer').click(function() {
			if (!move) {
				move = true;
				var state = $(this).parent().attr('class');
				if (state == 'closed') {
					$(this).next().slideDown(500, function() {
						move = false;
						resize();
					});
					$(this).parent().removeClass('closed').addClass('open');
				}
				else {
					$(this).next().slideUp(500, function() {
						move = false;
						resize();
					});
					$(this).parent().removeClass('open').addClass('closed');
				}
			}
		});

		$('#radio1 input').click(function() {
			updateValues();
		});
		$('#radio2 input').click(function() {
			calculate();
		});
		
		
		$('#offers .subscribe').click(function() {
			var href = $(this).attr('href');
			var values = '';
			for (var i=0; i<slider_values.length; i++) {
				values += slider_values[i]+'|';
			}
			values += $('input[name="radio2"]:checked').val();
			
			$.get("/save.php?values="+values, function(data){
				window.location.href = href;
			});
			
			return false;
		});
		
		$('#upgrades').css('cursor','pointer').click(function() {
			window.location.href = $('#header .subscribe').attr('href');
		});
	}
	
	//----------> FAQ
	
	var total_height = 0;
	
	$('.question_answer').each(function() {
		total_height += $(this).height()+32;
		if (!$(this).next().hasClass('question_answer')) {
			$(this).parent().css('height',total_height-2);
			total_height = 0;
		}
	});
	
	$('.question_categories .closed .more').css('display','none');
	
	$('.question_categories h2').css('cursor','pointer').click(function() {
		if (!move) {
			move = true;
			var state = $(this).parent().attr('class');
			if (state == 'closed') {
				$(this).next().slideDown(500, function() {
					move = false;
					resize();
				});
				$(this).parent().removeClass('closed').addClass('open');
			}
			else {
				$(this).next().slideUp(500, function() {
					move = false;
					resize();
				});
				$(this).parent().removeClass('open').addClass('closed');
			}
		}
	});
	
	//----------> WHERE
	
	if ($('body').attr('id') == 'where') {
		if ($('#col_left .button').attr('rel')) {
			$('#col_left .button').click(function() {
				var href = $(this).attr('href');
				var search = window.location.search;	
				var id = $('#col_left .button').attr('rel');
				
				$.get("/advanced.php?id="+id, function(data){
					window.location.href = href;
				});

				return false;
			});
		}
	}
	
	//----------> CHALLENGE

	var n = 10;
	var status;
	
	function showOnlyFirst(n) {
		var i = 0;
		$('#challenge_ranking tr').each(function() {
			if (i > n) {
				$(this).hide();
			}
			i++;
		});
		status = 'first';
	}
	
	function showAll() {
		$('#challenge_ranking tr').show();
		status = 'all';
	}
	
	if ($('#challenge_ranking tr').length <= n+1) {
		$('#challenge_ranking .button').hide();
	}
	else {
		$('#challenge_ranking .button').click(function() {
			if (status == 'first') {
				showAll();
				$(this).text('< view less');
				resize();
			}
			else {
				showOnlyFirst(n);
				$(this).text('view more >');
				resize();
			}
			return false;
		});
	}
	
	showOnlyFirst(n);
	
	//----------> DEVICES
	
	if ($('body').attr('id') == 'how') {
		setInterval('updateDevices()', 3000);
	}
	
	//----------> FORMS
	
	$.alerts.dialogClass = 'box';
	$.alerts.overlayOpacity = 0.5;
	$.alerts.overlayColor = '#000';
	
	$('form').submit(function() {
		if ($('body').attr('id') == 'where') {
			$.post("/send.php?format=json", {
				phone: $('#phone').val(),
				firstname: $('#firstname').val(),
				lastname: $('#lastname').val(),
				email: $('#email').val(),
				status: $('#status').val(),
				a: $('input[name="a"]').val(),
				o: $('input[name="o"]').val(),
				l: $('input[name="l"]').val()
			},
		  	function(data) {
				$('div.error').remove();
				$('.error').removeClass('error');
			if (1 == 1) {
				//if (data.status == 'ok') {
					jAlert($('#ok').text(), 'Cherry');
					$('#where form')[0].reset();
				
				}
				else {
					jQuery.each(data.errors, function() {
						if (this.type == 'empty') {
							$('#'+this.field).addClass('error');
							$('#'+this.field).after('<div class="error">'+$('#error_empty').text()+'</div>');
						}
						if (this.type == 'email') {
							$('#'+this.field).addClass('error');
							$('#'+this.field).after('<div class="error">'+$('#error_email').text()+'</div>');
						}
						resize();
					});
				}
		  	}, "json");
		}
		else {
			if ($('body').attr('id') == 'home') {
				$.post("/save-email.php?format=json", {
					email: $('#newsletter .text').val()
				},
			  	function(data) {
					$('#result').css('visibility','hidden');
			    	if (data.status == 'ok') {
						jAlert($('#ok').text(), 'Cherry');
						$('form')[0].reset();
					}
					else {
						$('#result').css('visibility','visible');
					}
			  	}, "json");
			}
			else {
				if ($('body').attr('id') == 'challenge') {
					if (!$('#accept').is(':checked')) {
						jAlert('You have to accept the rules!', 'Cherry');
					}
					else {
						$.post("/challenge.php?format=json", {
							firstname: $('#firstname').val(),
							lastname: $('#lastname').val(),
							email: $('#email').val(),
							website: $('#website').val(),
							ptitcaptcha_key: $('#ptitcaptcha_key').val(),
							ptitcaptcha_entry: $('#ptitcaptcha_entry').val()
						},
					  	function(data) {
							$('div.error').remove();
							$('.error').removeClass('error');
					    	if (data.status == 'ok') {
								jAlert($('#ok').text()+' You\'ll receive your cherry URL by email!', 'Cherry');
								$('form')[0].reset();
							}
							else {
								jQuery.each(data.errors, function() {
									if (this.type == 'empty') {
										$('#'+this.field).addClass('error');
										$('#'+this.field).after('<div class="error">'+$('#error_empty').text()+'</div>');
									}
									if (this.type == 'email') {
										$('#'+this.field).addClass('error');
										$('#'+this.field).after('<div class="error">'+$('#error_email').text()+'</div>');
									}
									if (this.type == 'email2') {
										$('#'+this.field).addClass('error');
										$('#'+this.field).after('<div class="error">'+$('#error_email2').text()+'</div>');
									}
									if (this.type == 'captcha') {
										$('#'+this.field).addClass('error');
										$('#'+this.field).after('<div class="error">'+$('#error_captcha').text()+'</div>');
									}
									if (this.type == 'url') {
										$('#'+this.field).addClass('error');
										$('#'+this.field).after('<div class="error">'+$('#error_url').text()+'</div>');
									}
									resize();
								});
							}
					  	}, "json");
					}
				}
				//old test form, now BETA sign up
				else {
					if ($('body').attr('id') == 'beta') {
						$.post("/send.php?format=json", {
							name: $('#name').val(),
							email: $('#email').val(),
							phone: $('#phone').val(),
							os: $('#os').val(),
							model: $('#model').val(),
							carrier: $('#carrier').val(),
							a: $('input[name="a"]').val(),
							l: $('input[name="l"]').val()
						},
					  	function(data) {
							$('div.error').remove();
							$('.error').removeClass('error');
					    	if (data.status == 'ok') {
								jAlert($('#ok').text(), 'Cherry');
								$('form')[0].reset();
							}
							else {
								jQuery.each(data.errors, function() {
									if (this.type == 'empty') {
										$('#'+this.field).addClass('error');
										$('#'+this.field).after('<div class="error">'+$('#error_empty').text()+'</div>');
									}
									if (this.type == 'email') {
										$('#'+this.field).addClass('error');
										$('#'+this.field).after('<div class="error">'+$('#error_email').text()+'</div>');
									}
									resize();
								});
							}
					  	}, "json");
					}
					else {
						$.post("/send.php?format=json", {
							name: $('#name').val(),
							email: $('#email').val(),
							subject: $('#subject').val(),
							comment: $('#comment').val(),
							phone: $('#phone').val(),
							a: $('input[name="a"]').val()
						},
					  	function(data) {
							$('div.error').remove();
							$('.error').removeClass('error');
					    	if (data.status == 'ok') {
								jAlert($('#ok').text(), 'Cherry');
								$('form')[0].reset();
							}
							else {
								jQuery.each(data.errors, function() {
									if (this.type == 'empty') {
										$('#'+this.field).addClass('error');
										$('#'+this.field).after('<div class="error">'+$('#error_empty').text()+'</div>');
									}
									if (this.type == 'email') {
										$('#'+this.field).addClass('error');
										$('#'+this.field).after('<div class="error">'+$('#error_email').text()+'</div>');
									}
									resize();
								});
							}
					  	}, "json");
					}
 				}
			}
		}
		return false;
	});
	
	//----------> RESIZE
	
	setTimeout('resize()',200);
	$(window).resize(function() {
		resize();
	});
	
	if ($.browser.msie && $.browser.version=="6.0") {
		if($("body").attr("id")=="home"){
			$("#header").pngFix(); 
			$("#footer").pngFix(); 
			$("#extra_div1").pngFix();
		}else{
			$(document).pngFix(); 
		}
		
	}
	
});