/**
 * @author mrkistic
 */

/**
 * resources
 */
	var arrTips = new Array("Pick me!", "I'm the best", "You'll love this", "You know you want to...", "Yes, yes, yes!", "You'll love me", "It's all about me", "I am the greatest", "You'll be amazed", "This is brilliant", "You have to do this", "A once in a lifetime...", "Don't miss this", "Look at me", "Please choose me", "That tickles");
	
	var arrRLEs = new Array(
		{id: '1_ASF_tapas', 'brox': 'brox_europe', 'code':'ASF', 'title':'Following the tapas trail...', 'name':'Paris to Madrid', 'text':"Take time out from San Sebastian\'s sparkling beaches to make your own tapas trail through the Old City. Hop between elegant cafes to sample small bite sized tapas, washed down with a local wine. When you\'ve savoured calamares, gambas or empanadas move on to the next café for more mouth-watering dishes. ¡Delicioso!"},

		{id: '2_ZRR_cinque', 'brox': 'brox_europe', 'code':'ZRR', 'title':'Wandering through cliff-top villages...', 'name':'Highlights of Italy', 'text':"Head away from the crowds to the high cliff tops above the Cinque Terre.  Follow rambling paths for breathtaking views over olive groves, vineyards, quaint villages and the shimmering sea below.  Drop down to the villages now and then to feast on fresh seafood, explore winding cobbled laneways and soak up the relaxed coastal lifestyle."},
		
		{id: '3_ORM_ger', 'brox': 'brox_asia', 'code':'ORM', 'title':'Spending the night in a ger...', 'name':'Tracks to Russia', 'text':"Try life as a nomad out in the wild landscapes of Mongolia and spend the night in a colourful, traditional ger. Sample traditional food and drink,  ride through the countryside on a sturdy Mongolian horse, and chat with local nomad families - before long you\'ll feel right at home. "},
		
		{id: '4_HSG_ganges', 'brox': 'brox_asia', 'code':'HSG', 'title':'Waking up on the Ganges...', 'name':'Slowly down the Ganges', 'text':"Wake up to the sounds of the holy River Ganges lapping outside your boat. The Ganges is the lifeblood of much of India and at sunrise you\'ll see the world awake on its shores - people bathing in its holy waters, worshipping the rising sun, washing clothes and even the conclusion of life, on riverside cremations."},

		{id: '5_CSA_china', 'brox': 'brox_asia', 'code':'CSA', 'title':'Walking the Great Wall...', 'name':'Iconic China', 'text':"A walk along the Great Wall is enough to render you speechless. And when you do it far away from the tourist hordes you are free to contemplate the 6,000 km (3,700 miles) of ancient wall stretching out around you. With barely another soul in sight, the scale and grandeur of the wall is awe-inspiring."},
		
		{id: '6_LRK_laos', 'brox': 'brox_asia', 'code':'LRK', 'title':'Giving alms to monks...', 'name':'Tap into Laos', 'text':"Rise early to join the locals giving alms to monks. This awe-inspiring ancient ritual is played out daily as people line the streets and distribute sticky rice, bananas and curries to hundreds of saffron clad monks that file past. Have some rice ready - you may make merit for giving offerings to them!"},

		{id: '7_PSC_farmstay', 'brox': 'brox_australasia', 'code':'PSC', 'title':'Helping out on an outback farm...', 'name':'Queensland Adventure', 'text':"Learn about life on the land at a working cattle station. Sleep out under an outback sky in a traditional Aussie swag (heavy sleeping bag) and give a helping hand around the farm. You\'ll be lassoing, mustering, milking and whip-cracking in no time. What fun! "},
		
		{id: '8_PSZ_glacier', 'brox': 'brox_australasia', 'code':'PSZ', 'title':'Climbing a glacier...', 'name':'Land of the long white cloud', 'text':"Feel cool in more ways than one as you strap on crampons for a walk on a glacier. In the company of an experienced guide, take an unforgettable hike through a world of rock and ice. White, blue and grey formations surround you, creating a spectacular, icy wonderland.  "},
		
		{id: '9_UOF_namibia', 'brox': 'brox_africa', 'code':'UOF', 'title':'Spotting the Big Five...', 'name':'Cape Town to Vic Falls', 'text':"Go on the hunt (with a camera) for Africa\'s Big Five: rhinos, lions, buffaloes, elephants and leopards. If you miss them during the day, you\'ll almost certainly hear them at night as you settle in to your bush camp in the wilds of Africa."},
		
		{id: '10_UOB_masai', 'brox': 'brox_africa', 'code':'YOI', 'title':'Trying Masai village life...', 'name':'Kenya Wildlife Safari', 'text':"Experience life as a Masai on a visit to a traditional village. Meet the proud Masai people, visit their homes and learn from the experts how to milk cattle, throw spears and dance like a true warrior."},
		
		{id: '11_DOO_mali', 'brox': 'brox_africa', 'code':'DOO', 'title':'Meeting the people of Timbuktu...', 'name':'The best of Mali and Ghana', 'text':"This legendary trading town is full of Tuareg history and culture. Head out and mingle with the locals in their markets, mosques or on a sunset camel ride out to a nearby camp. In the evening search out a music spot to sit back and listen to exotic desert tunes."},
		
		{id: '12_ESI_nile', 'brox': 'brox_africa', 'code':'ESI', 'title':'Sailing down the Nile...', 'name':'Discover Egypt', 'text':"Experience life as an old-world explorer as you sail down the Nile. Many towns, villages and farms along the banks have gone unchanged for centuries. In the company of a Nubian crew, their traditional songs and delicious food, you\'ll have front row seats to see rural Egyptian life glide by. "},
		
		{id: '13_XSC_morocco', 'brox': 'brox_africa', 'code':'XSC', 'title':'Riding camels through the desert...', 'name':'Colours of Morocco', 'text':"Live out your Saharan fantasies as your trusty camel takes you up and over sand dunes to a desert camp. Join our Berber friends for a night of tall tales, traditional songs and a fire side feast. Don\'t be surprised if your dreams are dotted with visions of oases, desert dunes… and camels."},
		
		{id: '14_QSC_market', 'brox': 'brox_latin_america', 'code':'QSC', 'title':'Bargaining at a market...', 'name':'Mayan  Highlights', 'text':"Soak up the colourful mayhem of Chichicastenango markets. Jostle for space with traditionally dressed locals, haggle to your heart\'s content and ponder whether or not the whole Guatemalan population has turned up. Don\'t be surprised if you leave with a backpack overflowing with vibrant textiles, and hand made jewellery you won\'t find anywhere else."},
		
		{id: '15_GSQ_inca', 'brox': 'brox_latin_america', 'code':'GSQ', 'title':'Trekking the Inca Trail...', 'name':'Sacred Land of the Incas', 'text':"There\'s no greater satisfaction than conquering the Inca Trail, especially by the power of your happily exhausted legs. Find friends in strangers as you\'re cheered along this ancient path. Savour sips of tea as Andean day becomes starry night. And finally smile, as Machu Picchu is revealed through the misty morning sunlight."},
		
		{id: '16_GSF_galapagos', 'brox': 'brox_latin_america', 'code':'GXF', 'title':'Snorkelling in the Galapagos...', 'name':'Active Galapagos', 'text':"Explore underwater worlds as colourful and exotic as the ones above ground in the Galapagos. Mingle with playful sea lions, get a close look at marine iguanas and explore incredible volcanic coastlines as you snorkel through the island\'s turquoise waters."}
	);

/**
 * Popover class
 */
var Popover = new Class({

	/*
	 init
	*/
	initialize: function() {
		_TRIP_WIDTH = 730;
		_POP_WIDTH = 520;
		this.sTrip = '';
		this.overlay = new Element('div').setProperty('id', 'divOverlay').injectInside(document.body);
		this.overlay.className = 'popOverlay';
		// add event listeners
		this.eventKeyDown = this.keyboardListener.bindWithEvent(this);
		this.eventPosition = this.position.bind(this);

		this.title = 'Popover title';
		this.url = 'http://www.intrepidtravel.com/';
		this.fadeIn = new Fx.Style($('divFaq'), 'opacity', {duration: 250, wait: false});
		this.fadeOverlayIn = new Fx.Style($('divOverlay'), 'opacity', {duration: 350, wait: true, onComplete: this.getContents.bind(this)});
		this.fadeOut = new Fx.Style($('divFaq'), 'opacity', {duration: 250, wait: false, onComplete: this.fadeOut2.bind(this)});
		this.fadeOut2 = new Fx.Style($('divOverlay'), 'opacity', {duration: 350, wait: true, onComplete: this.hideOverlay.bind(this)});
		$extend(this, Element.prototype)
		$extend(this, new Events());
	},

	position: function() {
		this.overlay.setStyles({top: Window.getScrollTop()+'px', left: Window.getScrollLeft()+'px', height: Window.getHeight()+'px', width: Window.getWidth()+'px'});
	},

	keyboardListener: function(event) {
		// close the Popover when the user presses CTRL + W, CTRL + X, ESC
		if ((event.control && event.key == 'w') || (event.control && event.key == 'x') || (event.key == 'esc')) {
			this.close();
			event.stop();
		}		
	},

	/*
	 Property: show
		Sets overlay size and displays the windows
	*/
	show: function(sTrip) {
		if ($defined(sTrip))
			this.sTrip = sTrip;
		else
			this.sTrip = '';
		this.hideSelects();
		$$('.popDiv').each(function(el){
			if (this.sTrip != '')
				el.style.width = _TRIP_WIDTH + 'px';
			else
				el.style.width = _POP_WIDTH + 'px';
		}, this);
		/* deal with the video explicitly */
		if ($('flashvideo'))
			getFlashMovieObject('flashvideo').pauseVid();
		$('divOverlay').style.zIndex = 1000;	// indexLevel++;
		$('divOverlay').style.opacity = 0;
		$('divOverlay').style.display = 'block';
		this.position();
		this.fadeOverlayIn.custom(0.1, 0.8);
		var fn = 'addEvent';
		window[fn]('scroll', this.eventPosition)[fn]('resize', this.eventPosition);
		document[fn]('keydown', this.eventKeyDown);
		// calls getContents on completion
		return false;
	},
	
	fadeOut2: function() {
		this.fadeOut2.start(.8, 0);
		// will call this.hideOverlay on completion
	},
	
	close: function() {
		var fn = 'removeEvent';
		window[fn]('scroll', this.eventPosition)[fn]('resize', this.eventPosition);
		this.fadeOut.start(1, 0);
		// will call this.fadeOut2 on completion
	},
	
	hideOverlay: function() {
		this.showSelects();
		$('divFaq').style.display = 'none';
		$('divOverlay').style.display = 'none';
		$('dPopContent').setHTML('');
		this.fireEvent('onComplete');
	},
	
	getContents: function() {
		$('tdHintTitle').setHTML(this.title);
		myAjax = new Ajax(this.url, {method: 'get', onComplete: this.ajaxDone, binder: this}).request();
		this.posFaq();
		$('divFaq').style.zIndex = 1001;	// indexLevel++;
		$('divFaq').style.opacity = 0.1;
		$('divFaq').style.display = 'block';
		this.fadeIn.custom(0.1, 1);
	},
	
	posFaq: function() {
		if (this.sTrip != '') {
			$('divFaq').style.width = _TRIP_WIDTH + 'px';
		} else {
			$('divFaq').style.width = _POP_WIDTH + 'px';
		}
		if ($('divFaq').style.display == 'block') {
			/* get coords */
			faqCoords = $('divFaq').getCoordinates();
			ovCoords = $('divOverlay').getCoordinates();
			iHeight = faqCoords.height;
			iWidth = faqCoords.width;
		} else {
			iHeight = 200;
			if (this.sTrip != '')
				iWidth = _TRIP_WIDTH;
			else
				iWidth = _POP_WIDTH;
		}

		/* update divFaq dimension */
		// if height of faq is less then window height, move it to the middle
		if (iHeight < window.getHeight()) {
			$('divFaq').style.top = (window.getHeight() - iHeight)/2 +'px';
		}
		if (iWidth < window.getWidth()) {
			$('divFaq').style.left = (window.getWidth() - iWidth)/2 +'px';
		}

	},
	
	ajaxDone: function(sHTML, xml, binder) {

		/* update content */
		$('dPopContent').setHTML(sHTML);
		x = $('dPopContent').getElementsByTagName("script");
        for(var i=0;i<x.length;i++){
           eval(x[i].text);
        }
		binder.posFaq();

	},

	/*
	Property: hideSelects
		Hides all select HTML elements as well as embeds and objects
	*/
	hideSelects: function () {
		$$('select').each(function(element) {
			if (!$defined(element.oldVisibility)) {
				element.oldVisibility = element.style.visibility ? element.style.visibility : "visible";
				element.style.visibility = "hidden";
			}
		});
  },

  showSelects: function(){
		$$('select').each(function(element) {
			if ($defined(element.oldVisibility)) {
				// Why?? Ask IE
				try {
					element.style.visibility = element.oldVisibility;
				} catch(e) {
					element.style.visibility = "visible";
				}
				element.oldVisibility = null;
			}
			else {
				if (element.style.visibility)
					element.style.visibility = "visible";
			}
		});
  }

});
/**
 * end Popover class
 */

	
/**
 * create draggable photos
 */
	var indexLevel = 16;

	function fisherYates ( myArray ) {
	  var i = myArray.length;
	  if ( i == 0 ) return false;
	  while ( --i ) {
	     var j = Math.floor( Math.random() * ( i + 1 ) );
	     var tempi = myArray[i];
	     var tempj = myArray[j];
	     myArray[i] = tempj;
	     myArray[j] = tempi;
	   }
	}
	
	function randomisePics() {
		var arr = new Array ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 );
		fisherYates(arr);
		var draggables = $$('.dragger');
	  var i=0;
		cont_coords = $('sml_pics').getCoordinates();
		draggables.each(function(el){
			/* apply tooltip */
			/*
			if (isdefined('bDraggable') && bDraggable==true)
				el.title = 'Choose your experience! :: ' + arrTips[i];
			*/
			/* set coords */
			var bLeft = new Fx.Style(el, 'left', {duration:1500, transition: Fx.Transitions.Elastic.easeOut});
			var bTop = new Fx.Style(el, 'top', {duration:1500, transition: Fx.Transitions.Elastic.easeOut});
			el.style.zIndex = arr[i++];
			coords = el.getCoordinates();
			iX = cont_coords.width - coords.width;
			iY = cont_coords.height - coords.height;
			x = $random(1, iX);
			y = $random(1, iY);
			bLeft.start(0, x);
			bTop.start(100, y);
			el.style.left = x;
		});
		if (isdefined('bDraggable') && bDraggable==true) {
			$('selP').selectedIndex = arr[0];
			selChange($('selP'));
			/* add tooltips */
			/*
			myTips = new Tips(draggables, {
				maxTitleChars: 150   // I like my captions a little long
			});
			*/
		}
	}

	function dragContainerInit(el) {
		var fadeIn = new Fx.Style(el, 'opacity', {duration: 100, wait: false});
		var bounce = new Fx.Style(el, 'margin', {duration:1500, transition: Fx.Transitions.elasticOut, wait: true});
    el.bounce = bounce;
		el.fadeIn = fadeIn;
		var dragContainerOptions = {
      handle: el,
			container: 'sml_pics',

			onStart: function(img){
        // clearTips();
				fadeIn.custom(1, 0.5);
        indexLevel++;
        el.style.zIndex = indexLevel;
      }.bind(this),
			
      onComplete: function(img){
				fadeIn.custom(0.5, 1);
				bounce.start(3,0);
				setDetails(el.id);
      }.bind(this)
    };

    el.style.cursor = 'move';
    el.makeDraggable(dragContainerOptions);
	}	// end function

	function setDetails(id) {
		if (isdefined('bDraggable') && bDraggable==true) {
			var opt = $('selP').options;
			for (var i=0; i<opt.length; i++) {
				if (id == opt[i].value)
					$('selP').selectedIndex = i;
					updateContent();
			}
		}
		$(id).style.filter = $(id).getProperty('stored_filter');
	}
	
	function selChange(sel) {
		if (sel.value != '') {
			indexLevel++;
			el = $(sel.value);
			el.style.zIndex = indexLevel;
			el.bounce.start(5, 0);
			updateContent();
		}
	}
	
	var sPage = '';
	var toVid;
	
	function getFlashMovieObject(movieName) {
		if (window.document[movieName]) {
			return window.document[movieName];
		}
		if (!window.ie) {
			if (document.embeds && document.embeds[movieName])
				return document.embeds[movieName]; 
		} else {
			return $(movieName);
		}
	}

	function updateContent() {
		selP = $('selP');
		var ind = selP.selectedIndex;
		var v = selP.value;
		var s = selP.options[ind].text;
		if (v != sPage) {
			$('dVideo').style.backgroundImage = '';
			clearTimeout(toVid);
			sPage = v;
			// var myAjax = new Ajax('content/'+s+'.html', {method: 'get', update: 'dContent'}).request();
			/* update header image */
			var sImg = 'images/framework/headers/'+v+'.gif';
			$('imgCHeader').src = sImg;
			/* update swf */
			$('dVideo').setHTML('<img src="video/stills/'+v+'.jpg" />');
			toVid = setTimeout('setVideo()', 2500);
			/* update text */
			sC = arrRLEs[ind-1].text; 
			$('pC').setHTML(sC);
			/* update link */
			$('ancC').name = v;
			$('ancC').setStyle('visibility', 'visible');
			
			/* updte form element */
			$('txtRLE').value = s;
			/* set default brochure if present */
			sBrox = arrRLEs[ind-1].brox; 
            if ($('brox_select1') != null) {
    			$A($('brox_select1').options).each(function(opt){
    				if (opt.value == sBrox)
    					opt.selected = true;
    			});
            }
		}
	}
	
	function setVideo() {
		$('dVideo').style.backgroundImage = 'url(video/stills/bg.jpg)';
		if (window.ie6)
			var so = new SWFObject("video/rle.swf", "flashvideo", "221", "194", "8,0,0,0", "#ffffe5", false, 'high');
		else
			var so = new SWFObject("video/rle.swf", "flashvideo", "220", "194", "8,0,0,0", "#ffffe5", false, 'high');
		so.addParam("movie", "video/rle.swf");
		so.addParam("allowScriptAccess", "sameDomain");
		so.addParam("loop", "false");
		so.addParam("quality", "high");
		so.addParam("bgcolor", "#ffffe5");
		so.addParam("swliveconnect", "true");
		so.addParam("wmode", "transparent");
		so.addVariable("sFileName", "flvs/"+sPage+".flv");
		so.write("dVideo");
	}
	
	function showTripDetails(s) {
		/* stop any flash showing */
		clearTimeout(toVid);
		/* get trip details */
		var rle = getRLE(s);
		/* set popover info */
		oPop.title = '&nbsp;' + rle.name + ' (' + rle.code + ')';
		oPop.url = 'tripInfo.php?code='+rle.code;
		/* show popover */
		oPop.show(s);
		return false;
	}
	
	function clearTips() {
		$$('.tool-tip').each(function (el) {
			el.style.display = 'none';
		});
	}
	
	function getRLE(id) {
		var retItem;
		arrRLEs.each(function (item) {
			if (item.id == id) {
				retItem = item;
			}
		});
		return retItem;
	}
	
	function openPopWindow(sTitle, sURL) {
		clearTimeout(toVid);
		// oPop.title = sTitle;
		oPop.title = '&nbsp;<img alt="win 30 trips in 30 days..." src="images/headingpopup.gif"/>';
		oPop.url = sURL;
		oPop.show();
		return false;
	}
	
	function closePop() {
		oPop.close();
		return false;
	}
	
	function ensureVideo() {
		if (isdefined('bDraggable') && bDraggable==true && !$('flashvideo'))
			toVid = setTimeout('setVideo()', 2500);
	}
    
    function ensureWinButton() {
        /* Required due to IE unreliability */
        $('clicktoenter').style.display = 'block';
    }

	function isdefined(variable) {
    return (typeof(window[variable]) == "undefined")?false:true;
	}
	
	var myTips;	// tooltip object
	var oPop;	// Popover class object

	window.addEvent('domready',function() {
		oPop = new Popover;
		oPop.addEvent('onComplete', ensureVideo);
	});
	
	function showHideIntrepidBrochure()
	{	
		if (document.getElementById('intrepid_brochure').checked == true){
			document.getElementById('intrepidBrochures').style.display = 'block';
		}
		else {
			document.getElementById('intrepidBrochures').style.display = 'none';
			document.getElementById('brox_select1').selectedIndex = 0;
			document.getElementById('brox_select2').selectedIndex = 0;
		}
	}
	
	function additValidationComp() {
        if(document.getElementById('gendermale').checked == false && document.getElementById('genderfemale').checked == false){
            alert('Please enter your gender');
            return false;
        } else {                   
            // All good
            fixSubscriptions(frmvalidator);
            return true;
        }
    }

    // This _must_ be the last JS function called
    function fixSubscriptions(frmvalidator) {
        var regExpSubscription = /^subscribe_.+$/;
        var el, i = 0;
        while (el = frmvalidator.formobj.elements[i++]) {
          if (el.type == 'checkbox' && el.name.match(regExpSubscription) && el.checked == false) {
            var newEl = document.createElement('input');
            newEl.type = 'hidden';
            newEl.name = el.name;
            newEl.id = el.id;
            newEl.value = '0';
            el.name = '';
            el.id = '';
            frmvalidator.formobj.appendChild(newEl);
          }
        }
        return true;
    }
