/**
 * Flight Centre New Zealand utility methods
 *
 * @author          Richard Gustin
 * @modifiedby      $LastChangedBy$
 * @copyright       Copyright Flight Centre Ltd. All rights reserved.
 * @version         $Revision$
 * @lastmodified    $Date$
 * @requires        FCL, FCL.UTIL, FCL.FORMS
 */

;FCNZ.UTIL =

{
	name: 'FCNZ.UTIL',
	
	init: function() {
		var _this = this;
		if ($('#enquiryOptions')) {
			$(document).ready(function(){
				_this.setupEnquiryOptionsComponentTracking();
			});
		}

		/**
		 * Initialise the alignColumnPricesWithCaret function
		 */
		if( $('.anotate') )
		{
			$(document).ready(function()
			{
				_this.alignColumnPricesWithCaret();
			});
		}
	},
    
	/**
     * Code that needs to be executed on every page load
     */
	putPCTTrackingCode: function(pctCode)
	{
		var dd = new Date();
		var ord = Math.round(Math.abs(Math.sin(dd.getTime()))*1000000000)%10000000;
		var script = document.createElement('script');
		script.type = 'text/javascript';
		script.src = 'http://adsfac.net/pct_mx.asp?L='+ pctCode +'&source=js&ord="'+ ord;
        
		$('head').append(script);
	},
    
	/**
     * Code to setup the enquiry options links
     */
	setupEnquiryOptionsComponentTracking: function() {
		var items = $('#enquiryOptions a');
		$.each(items, function(i)
		{
			$(items[i]).click(function(e)
			{
				e.preventDefault();
    			
				var trackerName = $(this).data('trackerName');
				trackerName = trackerName || false;
				var href = $(this).attr('href');
    			
				if (trackerName != false)
				{
					pageTracker._trackPageview(trackerName);
				}
    			
				var Reg = new RegExp('javascript:(.*)','i');
				if (Reg.test(href)) {
					setTimeout(RegExp.$1, 1000);
				} else {
					setTimeout('window.location.href = "'+href+'";', 1000);
				}
				return false;
			});
		});
	},
    
	highLightRow: function(target, color) {
		$(target).css({
			background: color
		});
	},
    
	highLightRowGrey: function(targetE1) {
		targetEl.style.background="#f1f1f1";
	},
	dehighLightRowGrey: function(targetE1) {
		targetEl.style.background="#ffffff";
	},

	fixBrokenProductImages: function($element)
	{
		$element.each(function()
		{
			if($(this).fclIsImageBroken() === true)
			{
				$(this).attr('src', 'http://www.flightcentre.co.nz/cms_images/web_images/products/default-generic.gif');
			}
		})
	},

	/**
	 * Supplied a list of class names, this function checks that the element
	 * contains a caret symbol and then applies a class name of caret for styling
	 */
	alignColumnPricesWithCaret: function()
	{
		$('.anotate').each(function(i, item)
		{
			if($(item).text().match(/^\^$/))
			{
				$(item).addClass('caret');
			}
		});
	},

	/**
	 * @description Prvoide the id of a container with elements that have class 'productLine'
	 * and only show the elements whose index is in elements array
	 * @param id string Parent element id
	 * @param elements array List of indexes of elements to show
	 * @return boolean True if operation completes successfully or false if an error occurs
	 * @usage FCL.UTIL.filterProductlineElementsList('usa-mexico-flights', [1, 4, 5]); // Shows elements with index 1, 4 and 5
	 */
	filterProductlineElementsList: function(id, elements)
	{
		/* Ensure id exists */
		el = jQuery('#'+id);
		if(el.length == 0)
		{
			FCL.UTIL.log('Element #'+ id +' not found');
			return false;
		}

		/* Hide all */
		el.children().hide();

		/* Then show the elements supplied in elements */
		for(i=0; i<elements.length; i++)
		{
			el.children(':nth-child('+ elements[i] +')').show();
		}

		return true;
	},


	/**
	 * @description Prvoide the id of a container plus the start and finish indexes of the elements
	 * to display. If the elements you want to display are not in a sequence, please use filterProductlineElementsList
	 * method instead.
	 * @param id string Parent element id
	 * @param start integer Start index (optional - deafault is 0)
	 * @param end integer End inde (optional)
	 * @return boolean True if operation completes successfully or false if an error occurs
	 * @usage FCL.UTIL.filterProductlineElementsSequence('usa-mexico-flights', 1, 2); // Shows elements with index 1 and 2
	 */
	filterProductlineElementsSequence: function(id, start, finish)
	{
		el = jQuery('#'+id);
		if(el.length == 0)
		{
			FCL.UTIL.log('Element #'+ id +' not found');
			return false;
		}

		start = (typeof start !== 'undefined') ? start: 0;
		finish = (typeof finish !== 'undefined') ? finish: el.find('.productLine').length;

		/* Hide all */
		el.children().hide();

		/* Show elements greater than start */
		/* Then show the elements supplied in elements */
		for(i=start; i<=finish; i++)
		{
			el.children(':nth-child('+ i +')').show();
		}

		return true;
	},


	/**
	 * @function RTWSelectSetup
	 * Dynamically changes the value of the hidden mode input field if
	 */
	RTWSelectSetup: function( $region, $mode)
	{
		//get orig value of the mode input and attach as data
		$mode.data('orig', $mode.val());
		var _this = this;

		//attach listener for change on region select
		$region.change(function(event)
		{
			var regionVal = $(event.currentTarget).val();


			switch( regionVal )
			{
				case 'specialists~29901':
					$mode.val('RTW_enquiry');
					break;
				default:
					$mode.val( $mode.data('orig') );
					break;
			}
		});

	},

	createExcerpts: function(elems,length,more_txt)
	{
		/*so it can handle mutiple elements*/
		$.each($(elems), function() {
			var item_html = $(this).html();
			item_html = item_html.replace(/<\/?[^>]+>/gi, ''); /*replace html tags*/
			item_html = jQuery.trim(item_html);  /*trim whitespace*/
			$(this).html(item_html.substring(0,length)+more_txt);  /*update the html on page*/
		});
		return this; /*allow jQuery chaining*/
	},



    fixBrokenProductImages: function($element)
    {
        $element.find('img').each(function()
        {
            if($(this).fclIsImageBroken() === true)
            {
                $(this).attr('src', '/cms_images/web_images/products/default-generic.gif');
            }
        })
    },

	clearForm: function(form) {
	  // iterate over all of the inputs for the form
	  // element that was passed in
	  $(':input', form).each(function() {
		
		var type = this.type;
		var tag = this.tagName.toLowerCase(); // normalize case
		
		// it's ok to reset the value attr of text inputs,
		// password inputs, and textareas
		if (type == 'text' || type == 'password' || tag == 'textarea')
		  
		  this.value = "";
		
		// checkboxes and radios need to have their checked state cleared
		// but should *not* have their 'value' changed
		else if (type == 'checkbox' || type == 'radio')
		  
		  this.checked = false;
		
		// select elements need to have their 'selectedIndex' property set to -1
		// (this works for both single and multiple select elements)
		else if (tag == 'select')
		  
		  this.selectedIndex = -1;
	  
	  });
	},
	
    fixBrokenProductImages: function($element)
    {
        $element.find('img').each(function()
        {
            if($(this).fclIsImageBroken() === true)
            {
                $(this).attr('src', '/cms_images/web_images/products/default-generic.gif');
            }
        })
    },
    /*

	 *	Set a maximum length of characters for a page element (used for tours search results)

	 *	Author: Sam Deering

	 */

	createExcerpts: function(elems,length,more_txt)

	{

		/*so it can handle mutiple elements*/

		$.each($(elems), function() {

			var item_html = $(this).html();

			item_html = item_html.replace(/<\/?[^>]+>/gi, ''); /*replace html tags*/

			item_html = jQuery.trim(item_html);  /*trim whitespace*/

			$(this).html(item_html.substring(0,length)+more_txt);  /*update the html on page*/

		});

		return this; /*allow jQuery chaining*/

	},
	/*

	 * $.stringToList - jQuery Function to convert a block of text into a html list.

	 * @requires: full stops after each sentence to match list elements

	 * @param: html element (div, span etc which contains the text)

	 * @param: list type (ul or ol)

	 * Usage: FC.UTIL.stringToList($('#inclusions'),'ul');

	 */

	stringToList: function(textContainer,listType) {

		

		// by default, we are not splitting the list

		var split = false;

		

		// if the container has HTML inside of it

		if (0) {

			

			// convert the raw html to workable content

			rawHTML = textContainer.html().replace(/<(?!\/?(b|strong|i|a)(?=>|\s? .*>))\/?.*?>/ig,''),

			sentenceRegex = /(?!(\.|{\d.\d})).*/igm, 

			htmlList = '<'+listType+'>';

			

			textContainer.html("");

			

			// for each line item discovered		

			$.each(rawHTML.match(sentenceRegex), function(i, v) {

				

				// if the lineitem is not a blank line

				if (v && (/[a-z0-9]+/igm.test(v))) {

				

					// ditch the br tag from the line item

					var s = v;

					s = s.replace(/<?(B|b)>/g,'~');

					s = s.replace(/<\//g,'');

						

					// convert the string to an array

					var a = s.split('~');

					

					var indexOfBR = v.indexOf('<BR>');

					var indexOfbr = v.indexOf('<br>');

					var indexOfB = v.indexOf('<B>');

					var indexOfb = v.indexOf('<b>');

						

					// if we can find a <B> tag - Internet Explorer only

					// or we found a lower case tag (non-IE browsers) and it's included mid-line

					// plus the bolded phrase is the last in the string (irrespective of a fullstop being after it and outside the bold tags)

					if (

						(indexOfBR != -1

						(indexOfB != -1 || indexOfb > 0) 

						&& (

							(

								a.length == 2 && (

									v.indexOf('<B>'+a[a.length-1]+'</B>') != -1 

									|| v.indexOf('<b>'+a[a.length-1]+'</b>') != -1

								)

							)

							|| 

							(

								a.length == 3 && a[a.length-1].replace(/[^a-z0-9]+/igm,'').length == 0 && (

									v.indexOf('<B>'+a[a.length-2]+'</B>') != -1 

									|| v.indexOf('<b>'+a[a.length-2]+'</b>') != -1

								)

							)

						)

					)) {

					

						// add the line item as a subtitle

						htmlList += '<li>' + a[0] + '</li>';

						

						// extract the row from the list output

						htmlList += '</'+listType+'><div>';

						htmlList += '<b>' + a[1] + '</b>';

						if (a.length == 3) htmlList += a[a.length-1];

						htmlList += '</div><'+listType+'>';

						

					// if we find a bold tag in general - non-IE browser

					// and the bolded phrase is the last in the string (irrespective of a fullstop being after it and outside the bold tags)

					} else if (

						(indexOfbr != -1 || indexOfBR != -1)

						&& indexOfb == 0

						&& (

							a.length == 3 && a[a.length-1].replace(/[^a-z0-9]+/igm,'').length == 0 && (

								v.indexOf('<B>'+a[a.length-2]+'</B>') != -1 

								|| v.indexOf('<b>'+a[a.length-2]+'</b>') != -1

							)

						)

					) {

					

						// extract the row from the list output

						htmlList += '</'+listType+'><div>';

						htmlList += '<b>' + a[1] + '</b>';

						if (a.length == 3) htmlList += a[a.length-1];

						htmlList += '</div><'+listType+'>';

							

					// if this is a normal line item

					} else {

					

						// show the line item

						htmlList += '<li>' + v + '</li>';

						

					}

					

				}

				

			});

			

			// end the list output

			htmlList += '</'+listType+'>';

			

			// show the pre-formatted HTML in the designated area

			textContainer.html(htmlList);

			

		}	

	},

	/*
	 * $.stringToList - jQuery Function to convert a block of text into a html list.
	 * @requires: full stops after each sentence to match list elements
	 * @param: html element (div, span etc which contains the text)
	 * @param: list type (ul or ol)
	 * Usage: FC.UTIL.stringToList($('#inclusions'),'ul');
	 */
	stringToList: function(textContainer,listType) {
		
		// by default, we are not splitting the list
		var split = false;
		
		// if the container has HTML inside of it
		if (0) {
			
			// convert the raw html to workable content
			rawHTML = textContainer.html().replace(/<(?!\/?(b|strong|i|a)(?=>|\s? .*>))\/?.*?>/ig,''),
			sentenceRegex = /(?!(\.|{\d.\d})).*/igm, 
			htmlList = '<'+listType+'>';
			
			textContainer.html("");
			
			// for each line item discovered		
			$.each(rawHTML.match(sentenceRegex), function(i, v) {
				
				// if the lineitem is not a blank line
				if (v && (/[a-z0-9]+/igm.test(v))) {
				
					// ditch the br tag from the line item
					var s = v;
					s = s.replace(/<?(B|b)>/g,'~');
					s = s.replace(/<\//g,'');
						
					// convert the string to an array
					var a = s.split('~');
					
					var indexOfBR = v.indexOf('<BR>');
					var indexOfbr = v.indexOf('<br>');
					var indexOfB = v.indexOf('<B>');
					var indexOfb = v.indexOf('<b>');
						
					// if we can find a <B> tag - Internet Explorer only
					// or we found a lower case tag (non-IE browsers) and it's included mid-line
					// plus the bolded phrase is the last in the string (irrespective of a fullstop being after it and outside the bold tags)
					if (
						(indexOfBR != -1
						(indexOfB != -1 || indexOfb > 0) 
						&& (
							(
								a.length == 2 && (
									v.indexOf('<B>'+a[a.length-1]+'</B>') != -1 
									|| v.indexOf('<b>'+a[a.length-1]+'</b>') != -1
								)
							)
							|| 
							(
								a.length == 3 && a[a.length-1].replace(/[^a-z0-9]+/igm,'').length == 0 && (
									v.indexOf('<B>'+a[a.length-2]+'</B>') != -1 
									|| v.indexOf('<b>'+a[a.length-2]+'</b>') != -1
								)
							)
						)
					)) {
					
						// add the line item as a subtitle
						htmlList += '<li>' + a[0] + '</li>';
						
						// extract the row from the list output
						htmlList += '</'+listType+'><div>';
						htmlList += '<b>' + a[1] + '</b>';
						if (a.length == 3) htmlList += a[a.length-1];
						htmlList += '</div><'+listType+'>';
						
					// if we find a bold tag in general - non-IE browser
					// and the bolded phrase is the last in the string (irrespective of a fullstop being after it and outside the bold tags)
					} else if (
						(indexOfbr != -1 || indexOfBR != -1)
						&& indexOfb == 0
						&& (
							a.length == 3 && a[a.length-1].replace(/[^a-z0-9]+/igm,'').length == 0 && (
								v.indexOf('<B>'+a[a.length-2]+'</B>') != -1 
								|| v.indexOf('<b>'+a[a.length-2]+'</b>') != -1
							)
						)
					) {
					
						// extract the row from the list output
						htmlList += '</'+listType+'><div>';
						htmlList += '<b>' + a[1] + '</b>';
						if (a.length == 3) htmlList += a[a.length-1];
						htmlList += '</div><'+listType+'>';
							
					// if this is a normal line item
					} else {
					
						// show the line item
						htmlList += '<li>' + v + '</li>';
						
					}
					
				}
				
			});
			
			// end the list output
			htmlList += '</'+listType+'>';
			
			// show the pre-formatted HTML in the designated area
			textContainer.html(htmlList);
			
		}	
	},
	
	//Set region-nav selected menu item 
    setPage: function(page)
	{
        $('#' + page).addClass('menudown').prepend('&raquo;');
	},

	/**
	 * If an error occurs, the error can be logged using Firebug's console.log feature. However, we needed
	 * to wrap access to this  in a function to detect if this happens on a browser without Firebug installed
	 * @param string Message to log
	 */
	log: function(message)
	{
		try
		{
			console.log(message);
		}
		catch(e){}
	}

};
FCNZ.UTIL.init();
