/**
 * @author camathum
 */

jQuery.noConflict();
(function($){

	function callOnDomReady() {
		$('html').addClass('js-on'); // HTML class
		$('body').removeClass('js-off');
		
		// wait for the SWFObject DOM-Ready, so we can return a proper reference
		// to flash object
		swfobject.addDomLoadEvent(function(){
			$('div.flash').embedSWF();
		});
		
		programSlot();
		fancyBox();
		dropDownForwarder();
		mailProSubscriberValidator();
		setVideoPreviewImages();
		SFVideoportal();
	}
	
	
	/**
	 * Radio and TV program slot
	 */
	function programSlot(){
		$('div.slot div.items').scrollTo($('ul li.pos-1'), 800);
	}
	
	/**
	 * Method for the SFVideoportal
	 */
	function SFVideoportal(){
		$("a#sfvideoportal").fancybox(fancyBoxConfigSFVideo());
	}
	
	/**
	 * FANCY BOX: SF Video configuration
	 */ 
	function fancyBoxConfigSFVideo(){
		return {
			'autoDimensions'	: false,
			'width'         	: 623,
			'height'    		: 363,
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'onComplete'	:	function() {
				// hide the video on background (hack for IE)
				$("div.sfvideoportal object").hide();
				// copy the HTML-Code from the hidden input field (IE8 hack)
				var clone = $('input#embedded_src').attr("value");
				// remove HTML code, if exists
				$("#embedded object").remove();
				// insert new code
				$("#embedded").append(clone);
				
			},
			'onClosed'		: function() {
				$("div.sfvideoportal object").show();
			}
		}
	}
	
	
	/**
	 * FANCY BOX: Formats the title for the fancyBox
	 */
	function formatFancyBoxTitle(title, currentArray, currentIndex, currentOpts) {
		output =  '<div class="title">';
		output += (title && title.length ? '<b>' + title + '</b><br />' : '' );
		if(currentArray.length > 1){
			output += '<div class="paging-index">';
			output += 'Maletg ' + (currentIndex + 1) + ' da ' + currentArray.length;
			output += '</div>';
		}
		output += '</div>';
	    return output;
	}
	
	
	/**
	 * FANCY BOX
	 */
	function fancyBox(){
		$("a.grouped_elements").fancybox(fancyBoxConfig());
	}

	
	/**
	 * FANCY BOX - Configuration
	 */
	function fancyBoxConfig(){
		return {
			'titlePosition' : 'inside',
			'titleFormat'	: formatFancyBoxTitle
		};
	}
	
	
	/**
	 * DropDown forwarder
	 */
	function dropDownForwarder(){
		function forward(){
			window.location = $(this).val();
			return false;
		}
		$('form select.jumpMenu').change(forward);
	}
	
	
	/**
	 * Set the image-preview for the videos
	 */
	function setVideoPreviewImages(){
		$("dt>a>span.play").each(function() {
			// Get the dimensions of the preview image
			prevImg = $(this).prev();
			imgWidth = getEvenSize(prevImg.width()) ;
			imgHeight = getEvenSize(prevImg.height()) ;
			
			// Get dimensions of overlayed image-icon
			playIconDimension = 40;
			playIconWidth = getEvenSize(playIconDimension);
			playIconHeight = getEvenSize(playIconWidth);
			
			// Calculate the position of the playIcon
			posX = getCenteredPosition(imgWidth, playIconWidth);
			posY = getCenteredPosition(imgHeight, playIconHeight);
				
			setNewPosition($(this), posX, posY);
		 });
		
		
		/**
		 * If image size is uneven/odd, adapt size to even size
		 */
		function getEvenSize(size){
			if((size % 2) > 0){
				size = size -1;
			}
			return size;
		}
		
		/**
		 * Calculates the position to center a image over another
		 */
		function getCenteredPosition(parentSize, childrenSize){
			return ((parentSize / 2) - (childrenSize / 2));
		}
		
		/**
		 * Set a new position for a item
		 */
		function setNewPosition(item, posX, posY){
			$(item).css("top", posY +"px");
			$(item).css("left", posX +"px");
		}
	}
	
	
	/**
	 * mailPro subscriber validator
	 */
	function mailProSubscriberValidator(){
		// Validate the form before submitting
		$('#mailProSubscribe input[type="submit"]').click(function() {
			  alertTitle = "Las suandantas indicaziuns n'en betg correctas u mancan:\n";
			  alertMsg = "";
			  
			  // Used to validate a competition
			  alertMsg += validateCompetition();
			  // Validate form fields
			  alertMsg += validateEmail('awEmail', "e-mail"); 
			  alertMsg += isRadioFieldChecked('awchamp1', "titulaziun"); 
			  alertMsg += validateRequired('awchamp2', "num"); 
			  alertMsg += validateRequired('awchamp3', "prenum"); 
			  alertMsg += validateRequired('awchamp5', "NP"); 
			  alertMsg += validateRequired('awchamp6', "lieu"); 
			  alertMsg += validateBirthday('awchamp7', "data da naschientscha"); 
			  
			  if(!isNullOrEmpty(alertMsg)){
				  alert(alertTitle + alertMsg);
				  return false;
			  }
			  return true;
		});

		
		/**
		 * Used to validate a selection of a competition
		 */
		function validateCompetition(){
			if($('#mailProSubscribe ul.competition input[type="radio"]').length){
				// competition fields exist
				radioButtonValue = $('#mailProSubscribe ul.competition input[type="radio"]:checked').val();
				if((radioButtonValue == undefined) || (typeof radioButtonValue == 'undefined')){
					return formatedMsg("selecziun da concurrenza");
				}
			  }
			return "";
		}
		
		/**
		 * Validate email
		 */
		function validateEmail(fieldName, errMsg){
			fieldValue = getFormFieldValue(fieldName);
			return (isEmail(fieldValue)) ? "" : formatedMsg(errMsg);
		}
		
		/**
		 * validate if value is indicated
		 */
		function validateRequired(field, errMsg){
			fieldValue = getFormFieldValue(field);
			return (!isNullOrEmpty(fieldValue)) ? "" : formatedMsg(errMsg);
		}
		
		/**
		 * Validate birthday
		 */
		function validateBirthday(fieldName, errMsg){
			fieldValue = getFormFieldValue(fieldName);
			return (isBirthdate(fieldValue)) ? "" : formatedMsg(errMsg);
		}
		
	   /**
		 * Return the value of a form field
		 */
	   function getFormFieldValue(fieldName){
			return $('#mailProSubscribe input[name="' + fieldName + '"]').val();
	   }
	   
		/**
		 * Used to validate a form field
		 */
		function isRadioFieldChecked(fieldName, errMsg){
			return ($('#mailProSubscribe input[name="' + fieldName + '"]:checked').length < 1) ? formatedMsg(errMsg) : "";
		}
	
		/**
		 * Used to format a message
		 */
	   function formatedMsg(msg){
			return "- " + msg + "\n";
	   }
	   
	   /**
		 * Is email
		 */
	   function isEmail(value){
		   expr = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,8}$/; 
		   return isRegExValid(value,expr)
	   }

	   /**
		 * Is it a birthday format
		 */
	   function isBirthdate(value){
		   expr = /^[0-9]{2}\.[0-9]{2}\.[0-9]{4}$/;
		   return isRegExValid(value,expr)
	   }
	   /**
		 * Validate a regular expression
		 */
	   function isRegExValid(data, regex){
	       var reg = new RegExp(regex);
	       return reg.test(data);
	   }
	   
	   /**
		 * Trim function
		 */
	   String.prototype.trim = function() {
			return this.replace(/^\s+|\s+$/g,"");
		}
	   
	   /**
		 * Validate if value is null
		 */
	   function isNullOrEmpty(myVal){
		    return ((myVal.trim() == "") || (myVal == null) || (myVal == undefined) || (typeof myVal == 'undefined'));
	   }
	}
	
	
	
	
	$('html').addClass('js-on'); // html class
	$(callOnDomReady);
})(jQuery);

