/**
 * @author David
 */
 $(document).ready(function(){		
		/***************************
		* Start Products Details 
		****************************/
		hs.graphicsDir = 'highslide/graphics/';
		hs.align = 'center';
		hs.transitions = ['expand', 'crossfade'];
		hs.outlineType = 'rounded-white';
		hs.fadeInOut = true;
		//hs.dimmingOpacity = 0.75;

		// Add the controlbar
		hs.addSlideshow({
		//slideshowGroup: 'group1',
		interval: 5000,
		repeat: false,
		useControls: true,
		fixedControls: 'fit',
		overlayOptions: {
								opacity: .75,
								position: 'bottom center',
								hideOnMouseOut: true
							}
		});
		/***************************
		* End Products Details 
		****************************/	
		
		/***************************
		* Start Panel Effect 
		****************************/		
		var $panels = $('#slider .scrollContainer > div');   	var $container = $('#slider .scrollContainer');
		// if false, we'll float all the panels left and fix the width 	   // of the container	   
	   var horizontal = true;
	   // collect the scroll object, at the same time apply the hidden overflow	   // to remove the default scrollbars that will appear	  
	   var $scroll = $('#slider .scroll').css('overflow', 'hidden');
		// float the panels left if we're going horizontal
	   if (horizontal) {	        $panels.css({	            'float' : 'left',	            'position' : 'relative' // IE fix to ensure overflow is hidden
	        });		        // calculate a new width for the container (so it holds all panels)	       
	       $container.css('width', $panels[0].offsetWidth * $panels.length);	   }
		    // apply our left + right buttons    
    	$scroll        .after('<img class="scrollButtons left" src="img/scroll_down.png" />')        .before('<img class="scrollButtons right" src="img/scroll_up.png" />');		    if (window.location.hash) {	        trigger({ id : window.location.hash.substr(1) });	    } else {	        $('ul.navigation a:first').click();	    }		    var scrollOptions = {	        target: $scroll, // the element that has the overflow		        // can be a selector which will be relative to the target	        
	        items: $panels,		        navigation: '.navigation a',		        // selectors are NOT relative to document, i.e. make sure they're unique	  
	        prev: 'img.right', 	        next: 'img.left',		        // allow the scroll effect to run both directions
	        axis: 'xy',
	        // duration of the sliding effect		
		      duration: 500,		        // easing - can be used with the easing plugin: 	        // http://gsgd.co.uk/sandbox/jquery/easing/	        
	        easing: 'swing'	    };    // apply serialScroll to the slider - we chose this plugin because it     // supports// the indexed next and previous scroll along with hooking     // in to our navigation.    
    	$('#slider').serialScroll(scrollOptions);	$(".btn-slide").click(function(){		$("#panel").slideToggle("slow");		$(this).toggleClass("active"); return false;	});			$(".menu a").hover(function() {		$(this).next("em").animate({opacity: "show", top: "-75"}, "slow");	}, function() {		$(this).next("em").animate({opacity: "hide", top: "-85"}, "fast");	});	//Set css in Firefox (Required to use the backgroundPosition js)
	$('#shutter1').css({backgroundPosition: '0px 0px'});	$('#shutter2').css({backgroundPosition: '0px 0px'});	$('#shutter3').css({backgroundPosition: '0px 0px'});	$('#shutter4').css({backgroundPosition: '0px 0px'});
	$('#shutter5').css({backgroundPosition: '0px 0px'});	$('#shutter6').css({backgroundPosition: '0px 0px'});	$('#shutter7').css({backgroundPosition: '0px 0px'});	$('#shutter8').css({backgroundPosition: '0px 0px'});
	$('#shutter9').css({backgroundPosition: '0px 0px'});
	$('#shutter10').css({backgroundPosition: '0px 0px'});
	$('#shutter11').css({backgroundPosition: '0px 0px'});
	$('#shutter12').css({backgroundPosition: '0px 0px'});
	//Animate the shutter  	
	$(".link").hover(function(){		  $(this).parent().animate({backgroundPosition: '(0px -100px)'}, 500 );		}, function() {		  $(this).parent().animate({backgroundPosition: '(0px 0px)'}, 500 );	}); 
	/***************************
	* End Panel Effect 
	****************************/	

	/***************************
	* Start Promos Register 
	****************************/		

	$(".report").click(function(){
		// load the contact form using ajax
		$.post("http://www.sotecec.com/index.php/support/Email", function(data){
			// create a modal dialog with the data
			$(data).modal({
				close: false,
				overlayId: 'contact-overlay',
				containerId: 'contact-container',
				onOpen: contact.open,
				onShow: contact.show,
				onClose: contact.close
			});
		});
	});

	// preload images
	var img = ['cancel.png','form_bottom.gif','form_top.gif','form_top_ie.gif','loading.gif','send.png'];
	$(img).each(function () {
		var i = new Image();
		i.src = '../img/contact/' + this;
	});
	/***************************
	* End Promos Register 
	****************************/	 	
	/***************************
	* Start Subscriber Register 
	****************************/	 
		
	$("#signup").click(function(e){
		e.preventDefault();
		var message = '';
		var email = $('#email_add').val();

		if (!validateEmail(email)) {}
			
		else{
			$.post('index.php/coming/insert_subscriber', {
				subscriber_mail: email
			});
			$.post('index.php/support/sendEmail',{
				subscriber_mail: email
			});
			$("#email").load('index.php/coming/add_subscriber/', {}, function(){
				$(this).fadeIn('slow', function(){
					 //$.unblockUI();			
				});
			});
		}	
	});
	
	$('ul#brands').innerfade({
						speed: 1000,
						timeout: 2000,
						type: 'random_start',
						containerheight: '134px'
					});
	
	$.preloadCssImages();
	
	});/*Close Document Ready*/


/* Aux - Validate email */
function validateEmail(email) {
  var emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
  
  if(email == "") {
    inlineMsg('email','<strong>Error</strong><br />You must enter your email.',2);
    return false;
  }
  if(!email.match(emailRegex)) {
    inlineMsg('email','<strong>Error</strong><br />You have entered an invalid email.',2);
    return false;
  }
  return true;
}


// START OF MESSAGE SCRIPT //

var MSGTIMER = 30;
var MSGSPEED = 5;
var MSGOFFSET = 3;
var MSGHIDE = 3;

// build out the divs, set attributes and call the fade function //
function inlineMsg(target,string,autohide) {
  var msg;
  var msgcontent;
  if(!document.getElementById('msg')) {
    msg = document.createElement('div');
    msg.id = 'msg';
    msgcontent = document.createElement('div');
    msgcontent.id = 'msgcontent';
    document.body.appendChild(msg);
    msg.appendChild(msgcontent);
    msg.style.filter = 'alpha(opacity=0)';
    msg.style.opacity = 0;
    msg.alpha = 0;
  } else {
    msg = document.getElementById('msg');
    msgcontent = document.getElementById('msgcontent');
  }
  msgcontent.innerHTML = string;
  msg.style.display = 'block';
  var msgheight = msg.offsetHeight;
  var targetdiv = document.getElementById(target);
  targetdiv.focus();
  var targetheight = targetdiv.offsetHeight;
  var targetwidth = targetdiv.offsetWidth;
  var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);
  var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET;
  msg.style.top = topposition+10 + 'px';
  msg.style.left = leftposition + 'px';
  clearInterval(msg.timer);
  msg.timer = setInterval("fadeMsg(1)", MSGTIMER);
  if(!autohide) {
    autohide = MSGHIDE;  
  }
  window.setTimeout("hideMsg()", (autohide * 1000));
}

// hide the form alert //
function hideMsg(msg) {
  var msg = document.getElementById('msg');
  if(!msg.timer) {
    msg.timer = setInterval("fadeMsg(0)", MSGTIMER);
  }
}

// face the message box //
function fadeMsg(flag) {
  if(flag == null) {
    flag = 1;
  }
  var msg = document.getElementById('msg');
  var value;
  if(flag == 1) {
    value = msg.alpha + MSGSPEED;
  } else {
    value = msg.alpha - MSGSPEED;
  }
  msg.alpha = value;
  msg.style.opacity = (value / 100);
  msg.style.filter = 'alpha(opacity=' + value + ')';
  if(value >= 99) {
    clearInterval(msg.timer);
    msg.timer = null;
  } else if(value <= 1) {
    msg.style.display = "none";
    clearInterval(msg.timer);
  }
}

// calculate the position of the element in relation to the left of the browser //
function leftPosition(target) {
  var left = 0;
  if(target.offsetParent) {
    while(1) {
      left += target.offsetLeft;
      if(!target.offsetParent) {
        break;
      }
      target = target.offsetParent;
    }
  } else if(target.x) {
    left += target.x;
  }
  return left;
}

// calculate the position of the element in relation to the top of the browser window //
function topPosition(target) {
  var top = 0;
  if(target.offsetParent) {
    while(1) {
      top += target.offsetTop;
      if(!target.offsetParent) {
        break;
      }
      target = target.offsetParent;
    }
  } else if(target.y) {
    top += target.y;
  }
  return top;
}

// preload the arrow //
if(document.images) {
  arrow = new Image(7,80); 
  arrow.src = "img/msg_arrow.gif"; 
}

var contact = {
	message: null,
	open: function (dialog) {
		// add padding to the buttons in firefox/mozilla
		if ($.browser.mozilla) {
			$('#contact-container .contact-button').css({
				'padding-bottom': '2px'
			});
		}
		// input field font size
		if ($.browser.safari) {
			$('#contact-container .contact-input').css({
				'font-size': '.9em'
			});
		}

		var title = $('#contact-container .contact-title').html();
		$('#contact-container .contact-title').html('Cargando...');
		dialog.overlay.fadeIn(200, function () {
			dialog.container.fadeIn(200, function () {
				dialog.data.fadeIn(200, function () {
					$('#contact-container .contact-content').animate({
						height: 260
					}, function () {
						$('#contact-container .contact-title').html(title);
						$('#contact-container form').fadeIn(200, function () {
							$('#contact-container #contact-name').focus();

							// fix png's for IE 6
							if ($.browser.msie && $.browser.version < 7) {
								$('#contact-container .contact-button').each(function () {
									if ($(this).css('backgroundImage').match(/^url[("']+(.*\.png)[)"']+$/i)) {
										var src = RegExp.$1;
										$(this).css({
											backgroundImage: 'none',
											filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' +  src + '", sizingMethod="crop")'
										});
									}
								});
							}
						});
					});
				});
			});
		});
	},
	show: function (dialog) {
		$('#contact-container .contact-send').click(function (e) {
			e.preventDefault();
			// validate form
			if (contact.validate()) {
				$('#contact-container .contact-message').fadeOut(function () {
					$('#contact-container .contact-message').removeClass('contact-error').empty();
				});
				$('#contact-container .contact-title').html('Enviando...');
				$('#contact-container form').fadeOut(200);
				$('#contact-container .contact-content').animate({
					height: '80px'
				}, function () {
					$('#contact-container .contact-loading').fadeIn(200, function () {
						$.ajax({
							url: 'http://www.sotecec.com/index.php/support/Email',
							data: $('#contact-container form').serialize() + '&action=send',
							type: 'post',
							cache: false,
							dataType: 'html',
							complete: function (xhr) {
								$('#contact-container .contact-loading').fadeOut(200, function () {
									$('#contact-container .contact-title').html('Gracias!');
									$('#contact-container .contact-message').html(xhr.responseText).fadeIn(200);
								});
							},
							error: contact.error
						});
					});
				});
			}
			else {
				if ($('#contact-container .contact-message:visible').length > 0) {
					var msg = $('#contact-container .contact-message div');
					msg.fadeOut(200, function () {
						msg.empty();
						contact.showError();
						msg.fadeIn(200);
					});
				}
				else {
					$('#contact-container .contact-message').animate({
						height: '30px'
					}, contact.showError);
				}
				
			}
		});
	},
	close: function (dialog) {
		$('#contact-container .contact-message').fadeOut();
		$('#contact-container .contact-title').html('Hasta Pronto...');
		$('#contact-container form').fadeOut(200);
		$('#contact-container .contact-content').animate({
			height: 40
		}, function () {
			dialog.data.fadeOut(200, function () {
				dialog.container.fadeOut(200, function () {
					dialog.overlay.fadeOut(200, function () {
						$.modal.close();
					});
				});
			});
		});
	},
	error: function (xhr) {
		alert(xhr.statusText);
	},
	validate: function () {
		contact.message = '';
		if (!$('#contact-container #contact-name').val()) {
			contact.message += 'Nombre obligatorio. ';
		}

		var email = $('#contact-container #contact-email').val();
		if (!email) {
			contact.message += 'Correo obligatorio. ';
		}
		else {
			if (!contact.validateEmail(email)) {
				contact.message += 'Correo inv&aacute;lido. ';
			}
		}
		
		if (!$('#contact-container #contact-message').val()) {
			contact.message += 'Mensaje obligatorio.';
		}

		if (contact.message.length > 0) {
			return false;
		}
		else {
			return true;
		}
	},
	validateEmail: function (email) {
		var at = email.lastIndexOf("@");

		// Make sure the at (@) sybmol exists and  
		// it is not the first or last character
		if (at < 1 || (at + 1) === email.length)
			return false;

		// Make sure there aren't multiple periods together
		if (/(\.{2,})/.test(email))
			return false;

		// Break up the local and domain portions
		var local = email.substring(0, at);
		var domain = email.substring(at + 1);

		// Check lengths
		if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
			return false;

		// Make sure local and domain don't start with or end with a period
		if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
			return false;

		// Check for quoted-string addresses
		// Since almost anything is allowed in a quoted-string address,
		// we're just going to let them go through
		if (!/^"(.+)"$/.test(local)) {
			// It's a dot-string address...check for valid characters
			if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
				return false;
		}

		// Make sure domain contains only valid characters and at least one period
		if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
			return false;	

		return true;
	},
	showError: function () {
		$('#contact-container .contact-message')
			.html($('<div class="contact-error">').append(contact.message))
			.fadeIn(200);
	}
};
