/**
 * Javascript presentation class.
 * At release should contain all related javascript files.
 *
 * @project       digiinfo.com
 * @subpackage    web.presentation
 */
 
var basepath = null;
 
function setNewColor(index, animate, savecookie) {
	// get color from class
	$('#base-path').removeClass().addClass('color-' + index, 1000);
	var newColor = $('#base-path').css('background-color');
	
	// set color to body
	if (animate == true) {
		$('body')
		.animate( { backgroundColor: newColor }, 500);
	} else {
		$('body').css('background-color', newColor);
	}
	
	// save cookie
	if (savecookie == true) {
		$.cookie('backgroundcolor', index, { path: '/', expires: 7 } ); 
	}
	
	// save current state
	$('.light').attr('rel', index);
	
	// record state
	if (animate == true) {
		// only make updates when animating
		$sessionId = $.cookie('session_id');
		if ($sessionId) {
			// we have a cookie
		} else {
			// set a new cookie based ont the current sessions
			$sessionId = $('#session-id').attr('value');
			$.cookie('session_id', $sessionId, { path: '/', expires: 7 } ); 
		}
		
		$.ajax( 
		    { 
		        type: "POST", 
		        url: basepath + 'users/record_color', 
		        data: { 'session_id' : $sessionId, 'color_id' : index },
		        success: 
		            function(t) 
		            {
						//
		            }, 
		        error: 
		            function() 
		            { 
		                // error, nothing you can do
		            } 
		    });
	}
}
 
function lookup(string, target_url) {
	if (string.length > 0) {
		$.ajax( 
	    { 
	        type: "POST", 
	        url: target_url, 
	        data: { 'string': string },
	        success: 
	            function(t) 
	            {
					$('#suggestions').fadeIn();
					$('#suggestions').html(t);
					$('#main-search').removeClass('running');
	            }, 
	        error: 
	            function() 
	            { 
	                alert('Error performing quick search');
	            } 
	    });
	} else {
		$('#suggestions').fadeOut();
		$('#main-search').removeClass('running');
	}
}


$(document).ready(function(){
	
	basepath = $('#base-path').attr('value');
	var mycountry = $('#my-country').attr('value');
	
	
	
	$("#spot-slider").slides({
		generatePagination: false,
		play: 5000,
		generateNextPrev: false
	});

	if ($('#SampleName').length > 0) {
		// we have a sample request form
		$('#SampleName').keypress(function(e) {
			if ($(this).parent().next().css('display') != 'block')
			$(this).parent().next().slideDown();
		});
	};
	
	$('.toggle-netviewer').click(function() {
		$(this).parent().next().slideToggle();
		return false;
	});
	
	$('.adresa').each(function(item) {
		var addr = $(this).html();
		var splitAddr = addr.split(' ');
		
		$(this).html('Email: <a href="mailto:' + splitAddr[1] + '@' + splitAddr[3] + '">' + splitAddr[1] + '@' + splitAddr[3] + '</a>');
	});
	
	$('.search-container label').labelOver('over');
	
	$('.icon-down').click(function() {
		$(this).next().slideToggle();
		$(this).toggleClass('showing');
		return false;
	});
	
	$('.countries div.partner.' + mycountry).each(function() {
		$(this).css('background-color', '#FFCC00');
	});
	
	$('.reseller.' + mycountry).each(function() {
		$('#top-country').append($(this).html());
	});
	
	/*
	*	success stories toggler
	*/
	
	$('.toggle-story').click(function(e) {
		e.preventDefault();
		$('.success.showing').animate({opacity: 0}, 500).hide().removeClass('showing');
		$('#success-' + $(this).attr('rel')).addClass('showing').animate({opacity: 1}, 500).show();
		$.scrollTo( $('.success-container'), { speed: 700} ); 
		return false;
	});
	
	// make sidebar anchor links use scrollTo instead of the regular
	// abrupt scroll
	$('.anchors ul li a').click(function() {
		$.scrollTo( $(this).attr('href'), { speed: 700} ); 
		return false;
	});
	
	$('.light').click(function() {
		$(this).toggleClass('on');
		
		var currentColor = $(this).attr('rel');
		
		currentColor = parseInt(currentColor) + 1;
		if (currentColor > 5) {
			currentColor = 1;
		}
		
		setNewColor(currentColor, true, true);

		return false;
	});
	
	$('.big-link .content a').bigTarget();
	
	$('a.flash').click(function() {
		window.open($(this).attr('href'),'mywindow','width=620,height=510');
		return false;
	});
	
	$('a.flash-ink').click(function() {
		window.open($(this).attr('href'),'mywindow','width=930,height=700');
		return false;
	});
	
	$('.light').hover(
		function() {
			$(this).stop().animate({top: '1px'}, 300);
		},
		function() {
			$(this).stop().animate({top: '-9px'}, 500);
		}
	);
	
	$('#main-search').keyup(function(e) {
		if (e.keyCode == 13) {
			
			$(this).addClass('running');
			var searchString = $(this).val();
			
			clearTimeout($.data(this, "timer"));
			var ms = 200; //milliseconds
		    var val = this.value;
		    var wait = setTimeout(function() {
		    	
		      	lookup(searchString, basepath + 'products/autosearch');
		      	
		    }, ms);
		    $.data(this, "timer", wait);

		} else {
			$('#suggestions').fadeOut();
			$(this).removeClass('running');
		}
	});
	
	// preproofer sameple
	if ($('#SampleAddForm').length > 0) {
		// turn on live validation
		
		$('#SampleAddForm .submit input').click(function(e) {
			
			e.preventDefault();
			
			var sayName = new LiveValidation( "SampleName", { validMessage: "",  onlyOnSubmit: true } );
			sayName.add( Validate.Presence, {
				failureMessage: "Please fill in your name."
			});		
			
			var sayCompany = new LiveValidation( "SampleCompany", { validMessage: "",  onlyOnSubmit: true } );
			sayCompany.add( Validate.Presence, {
				failureMessage: "Please fill in your company name."
			});		
			
			var sayStreet = new LiveValidation( "SampleStreet", { validMessage: "",  onlyOnSubmit: true } );
			sayStreet.add( Validate.Presence, {
				failureMessage: "Please fill in the destination address for the Preproofer sample."
			});		
			
			var sayPostcode = new LiveValidation( "SamplePostcode", { validMessage: "",  onlyOnSubmit: true } );
			sayPostcode.add( Validate.Presence, {
				failureMessage: "Please fill in the postcode."
			});		
			
			var sayTown = new LiveValidation( "SampleTown", { validMessage: "",  onlyOnSubmit: true } );
			sayTown.add( Validate.Presence, {
				failureMessage: "Please fill in the town/city."
			});		
			
			var sayCountry = new LiveValidation( "SampleCountry", { validMessage: "",  onlyOnSubmit: true } );
			sayCountry.add( Validate.Presence, {
				failureMessage: "Please fill in the country name."
			});		
			
			var sayPhone = new LiveValidation( "SamplePhone", { validMessage: "",  onlyOnSubmit: true } );
			sayPhone.add( Validate.Presence, {
				failureMessage: "Please fill in a phone number."
			});		
			
			var sayFax = new LiveValidation( "SampleFax", { validMessage: "",  onlyOnSubmit: true } );
			sayFax.add( Validate.Presence, {
				failureMessage: "Please fill in a fax number."
			});		
			
			var sayEmail = new LiveValidation( "SampleEmail", { validMessage: "",  onlyOnSubmit: true } );
			sayEmail.add( Validate.Presence, {
				failureMessage: "Please fill in an email address."
			});		
			
			var areAllValid = LiveValidation.massValidate( [ sayName, sayCompany, sayStreet, sayPostcode, sayTown, sayCountry, sayPhone, sayEmail, sayFax ] );
			
			if (!areAllValid) return false;
			
			// insert loading element
			$('#SampleAddForm').before('<div class="loading2" id="loading-sample"></div>').slideUp();
			
			// return false;
			
			// send submit through ajax
			$('#SampleAddForm').ajaxSubmit({
				target: '#loading-sample',
				success: function() {
					// introdu manual element de lista cu noul nume introdus
					$('#loading-sample').removeClass('loading2');
					//$('#add-new-category').before('<li><span>' +  $newCategory + '</span></li');
				}
			});
		});
		
	}
	
	
	//
	//	reports delete
	//
	$('.job').hover(function() {
		$(this).find('.delete-job').stop().animate({
			top: '-20px',
			opacity: 1
		});
	}, function () {
		$(this).find('.delete-job').stop().animate({
			top: '0px',
			opacity: 0
		});
	});
	
	$('a.delete-job').click(function() {
		$element = $(this).parent();
		
		$(this).load( $(this).attr('href'), function () {
			$element.remove();
		});
		
		return false;
	});
	
	$('#NewsletterSubscribeForm .submit input').click(function (e) {
		e.preventDefault();
		
		$('<div class="processing"></div>').appendTo($('#NewsletterSubscribeForm'));
		
		$('#NewsletterSubscribeForm').ajaxSubmit({
			success: function (data) {
				$('#NewsletterSubscribeForm').html(data);
			}
		});
	});
	
	
	 $("#main-search").blur(function(){
	 	$('#suggestions').fadeOut();
	 });
	 
	 // gets called at page load
	var backColor = $.cookie('backgroundcolor');
	if (backColor != null) {
		// cookie is set yet
		$('.light').attr('rel', 1);
		setNewColor(backColor, false, false);
	} else {
		// use session variable
		$color = $('#random-color').attr('value');
		$('.light').attr('rel', 1);
		setNewColor($color, false, false);
	}
	
	clickHeatSite = '';
	clickHeatGroup = (document.title == '' ? '-none-' : encodeURIComponent(document.title));
	clickHeatServer = basepath + 'clickheat/click.php';
	initClickHeat(); 
	

});
