function dbg(val) {
	if ( typeof(console) != 'undefined' ) {
		if ( typeof(console.debug) != 'undefined' ) {
			console.debug(val);
		}
	}
}
function setCookie(c_name,value,expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
function getCookie(c_name)
{
	if (document.cookie.length>0) {
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1) { 
			c_start=c_start + c_name.length+1; 
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
				return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	return "";
}
function doNavigation(triptype,tripid) {
	if ( triptype == 'mls' ) {
		window.location = './trips.php?id='+tripid;
	}
	else if ( triptype == 'partner' ) {
		window.location = './partners.php?pid='+tripid;
	}
}
$.fn.selectOptionsById = function(optionid, clear)
{
	var v = optionid;
	var vT = typeof(optionid);
	var c = clear || false;
	// has to be a string or regular expression (object in IE, function in Firefox)
	if(vT != "string" && vT != "function" && vT != "object") return this;
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != "select") return this;
			// get options
			var o = this.options;
			// get number of options
			var oL = o.length;
			for(var i = 0; i<oL; i++)
			{
				if(o[i].id == v)
				{
				  o[i].selected = true;
				}
				else if(c)
				{
				  o[i].selected = false;
				}
			}
		}
	);
	return this;
};
$.fn.selectOptions = function(value, clear)
{
	var v = value;
	var vT = typeof(value);
	var c = clear || false;
	// has to be a string or regular expression (object in IE, function in Firefox)
	if(vT != "string" && vT != "function" && vT != "object") return this;
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != "select") return this;
			// get options
			var o = this.options;
			// get number of options
			var oL = o.length;
			for(var i = 0; i<oL; i++)
			{
        if(o[i].value == v)
        {
          o[i].selected = true;
        }
        else if(c)
        {
          o[i].selected = false;
        }
			}
		}
	);
	return this;
};


//dont overwrite MLS object if it exists already
if (typeof MLS == "undefined" || !MLS) {
    var MLS = {};
}

MLS.destinations = {

  //store handle to the scroller polling interval
  moveHandle:null,
  
  //how often to scroll destination box while hovering
  scrollSpeed:null,
  
  //how far to scroll each time scrollSpeed milliseconds pass
  scrollInterval:null,
  
  //current position of destination box scrolling
  curPosY:null,

  //min scroll
  minY:null,
  
  //max scroll
  maxY:null,
  
  //whether or not flash is ready to accept commands
  isFlashLoaded:false,
  
  hadHash: false,

  arrowUp: {
    state: 'disabled'
  },
  
  arrowDown: {
    state: 'disabled'
  },

  navigateToTrip: function(triptype,tripid) {
	doNavigation(triptype,tripid);
  },
  //establish mouse events on destination box scrolling
  initBoxes: function() {
  
    var a=arguments, startTop;

    //configuration and defaults
    this.scrollSpeed = a[0] || 30;
    this.scrollInterval = a[1] || 15;
    
    startTop = $('.mls_box_column1').css('top');
    
    this.curPosY = parseInt(startTop.substring(0, startTop.length - 2), 10);
    
    this.maxY = this.curPosY;
       
    this.updateSize();
        
    this.registerEventHandlers();
  
  },
  
  registerEventHandlers: function() {
    var that=this;
  
    $('.mls_dest_arrow_up').mouseover(function(){
      that.moveHandle = setInterval(
        function() {
          that.movedown();
        }, 
        that.scrollSpeed
      );
    });
    
    $('.mls_dest_arrow_up').mouseout(function(){
      clearInterval(that.moveHandle);
      if(that.curPosY < that.maxY) {
        that.arrowUp.state = 'normal';
        that.updateIcons();
      }
    });
    
    $('.mls_dest_arrow_down').mouseover(function(){
      that.moveHandle = setInterval(
        function() {
          that.moveup();
        }, 
        that.scrollSpeed
      );
    });
      
    $('.mls_dest_arrow_down').mouseout(function(){
      clearInterval(that.moveHandle);
      if(that.curPosY > that.minY) {
        that.arrowDown.state = 'normal';
        that.updateIcons();
      }
    });
    
    $('ul.countries li a.menutitle').click(function() {
      $(this).toggleClass("expanded").toggleClass("collapsed").find("+ ul").slideToggle("medium", function(){that.updateSize();});
    });
    
    $('#bread_crumb > ul > li').mouseover(function() {
      if(that.isFlashLoaded) {
        $(this).find('div').show();
      }
    });
    
    $('#bread_crumb > ul > li').mouseout(function() {
      $(this).find('div').hide();
    });
  },

  //up function (used by down arrow) called while scrolling upon fire of moveHandle polling
  moveup: function() {
    this.curPosY -= this.scrollInterval;
  
    if(this.curPosY < this.minY) {
      this.curPosY = this.minY;
      clearInterval(this.moveHandle);
      this.arrowDown.state = 'disabled';
    }
    else {
      if(this.curPosY <= this.maxY) {
        this.arrowUp.state = 'normal';
      }
      else {
        this.arrowDown.state = 'active';
      }
    }
    
    this.updateIcons();
    this.updatePos();
  },
  
  //down function (used by up arrow) called while scrolling upon fire of moveHandle polling
  movedown: function() {
    this.curPosY += this.scrollInterval;
    
    if(this.curPosY > this.maxY) {
      this.curPosY = this.maxY;
      clearInterval(this.moveHandle);
      this.arrowUp.state = 'disabled';
    }
    else {
      if(this.curPosY >= this.minY) {
        this.arrowDown.state = 'normal';
      }
      else {
        this.arrowUp.state = 'active';
      }
    }
    
    this.updateIcons();
    this.updatePos();
  },

  //change icons (normal, active, disabled)
  changeIcon: function(target, type) {
    switch(type) {
      case 'normal':
        $('.mls_dest_arrow_'+target).css('background-position','118px 0');
        break;
      case 'disabled':
        $('.mls_dest_arrow_'+target).css('background-position','118px -18px');
        break;
      case 'active':
        $('.mls_dest_arrow_'+target).css('background-position','118px -36px');
        break;
    }
  },

  updateSize: function() {
    if($('.countries').height() + this.maxY > $('.mls_dest_box').height()) {
      //Negative length of content and padding (represented by top boundary), minus 1 length of viewport
      this.minY = -($('.countries').height() + this.maxY - $('.mls_dest_box').height());
    }
    else {
      this.minY = this.maxY;
    }
    
    if(this.curPosY >= this.minY) {
      this.arrowDown.state = 'normal';
    }
    
    if($('.countries').height() < $('.mls_box_column1').height()) {
      this.arrowDown.state = 'disabled';
    }
    
    this.updateIcons();
  },

  updatePos: function() {
    $('.mls_box_column1').css('top',this.curPosY + 'px');
  },

  updateIcons: function() {
    this.changeIcon('up', this.arrowUp.state);
    this.changeIcon('down', this.arrowDown.state);
  },
  
  //synchronize views of flash and javascript objects
  switchView: function(continentid, continentlabel, countryid, countrylabel) {	
  
    var that=this, select, o, oL, i, menudiv1, menudiv2, has_mls, has_partner, mlstrips, partnertrips;
  
    $('.ajax').css('visibility','visible');
    this.continentid = continentid;
	this.countryid = countryid;
	dbg(continentid+' '+continentlabel+' '+countryid+' '+countrylabel);
	location.replace(unescape(location.href).replace(unescape(location.hash),'')+"#"+continentid+"_"+continentlabel+(typeof(countryid)!="undefined"?"_"+countryid+"_"+countrylabel:""));

	//destinations breadcrumb dropdown
    
    menudiv1 = '<div class="bread_continent"><ul>';

    $('#menu_' + continentid).next().children().each(function(){
      var cid, clabel, anchor;

      anchor = $(this).children()[0];

      cid = $(anchor).attr('id').substring(5);
      clabel = $(anchor).html();

      menudiv1 += '<li>';

      if($(anchor).next().find('.partner').length > 0) {
        menudiv1 += '<div class="right"><img src="images/icon_partner.gif" alt="" width="20" height="14" /></div>';
      }

      if($(anchor).next().find('.mls').length > 0) {
        menudiv1 += '<div class="right"><img src="images/icon_mls.gif" alt="" width="21" height="15" /></div>';
      }

      menudiv1 += '<a href="javascript:;" onclick="MLS.destinations.flashNav(\''+continentid+'\',\''+cid+'\');MLS.destinations.switchView(\''+continentid+'\',\''+continentlabel+'\',\''+cid+'\',\''+clabel+'\')">'+clabel+'</a></li>';

    });

    menudiv1 += '</ul></div>';
 
    if (continentid && continentlabel) {
 
      //selected a continent
    
      if(!countryid) {
        //update side menu
        
        $('.mls_box_column1').animate({top: that.maxY + 'px'},{
          complete: function() {
            $('.countries a.menutitle.expanded:not(#menu_'+continentid+')').removeClass('expanded').addClass('collapsed').find('+ ul').slideUp('medium');
            $('#menu_'+continentid).removeClass("collapsed").addClass('expanded').find('+ ul').slideDown('medium', function() {
              that.curPosY = that.maxY;
              that.updateSize();
                            
              //update breadcrumb
          
              $('#bread_continent_item').next().hide();
              $('#bread_country_item').hide();
                
              $('#bread_destination_item').next().show();  
              $('#bread_continent_item').html('<a href="javascript:;" onclick="MLS.destinations.flashNav(\''+continentid+'\');MLS.destinations.switchView(\''+continentid+'\', \''+continentlabel+'\')"><span class="current">'+continentlabel+'</span></a>'+menudiv1);    
              $('#bread_continent_item').show();
              
              
              //update quicknav
              
              $('#country_select').selectOptions(continentlabel);
              
              $('.ajax').css('visibility','hidden');
            });
          }
        });
      }
      //selected a country
      
      else {
        
        //update side menu
        
        $('.mls_box_column1').animate({top: that.maxY + 'px'}, {
          complete: function() {
            $('.countries a.menutitle.expanded:not(#menu_'+continentid+'):not(#menu_'+countryid+')').
            removeClass('expanded').addClass('collapsed').find('+ ul').slideUp('medium');
            
            $('#menu_'+continentid+', #menu_'+countryid).removeClass('collapsed').addClass('expanded').
            find('+ ul').slideDown('medium', function() {
              that.curPosY = that.maxY;
              that.updateSize();
              
              
              //update breadcrumb
                  
              menudiv2 = '<div class="bread_country">';
              
              mlstrips = $('#menu_' + countryid).next().children().find('a[class="mls"]');
              partnertrips = $('#menu_' + countryid).next().children().find('a[class="partner"]');
              
              if(mlstrips.length > 0) {
                menudiv2 += '<ul class="mls"><li><strong>MLS Destinations</strong></li>';
                mlstrips.each(function(){
                  var link = $(this).attr('href');
                  var name = $(this).html();
                  var onclick = $(this).attr('onclick') + '';
                  onclick = onclick.replace(/"/g,"'");
                  var onclick_stmts = onclick.split("\n");
                  
                  menudiv2 += '<li><a class="mls" onclick="'+onclick_stmts[1]+onclick_stmts[2]+'" href="'+link+'">'+name+'</a></li>';;
                });
                menudiv2 += '</ul>';
              }
              
              if(partnertrips.length > 0) {
                menudiv2 += '<ul class="partner"><li><strong>Partners</strong></li>';
                partnertrips.each(function(){
                  var link = $(this).attr('href');
                  var name = $(this).html();
                  var onclick = $(this).attr('onclick') + '';
                  onclick = onclick.replace(/"/g,"'");
                  var onclick_stmts = onclick.split("\n");
                  menudiv2 += '<li><a class="partner" onclick="'+onclick_stmts[1]+onclick_stmts[2]+'" href="'+link+'">'+name+'</a></li>';;
                });
                menudiv2 += '</ul>';
              }
              menudiv2 += '</div>';
              
              $('#bread_destination_item').next().show();  
              $('#bread_continent_item').html('<a href="javascript:;" onclick="MLS.destinations.flashNav(\''+continentid+'\');MLS.destinations.switchView(\''+continentid+'\', \''+continentlabel+'\')">'+continentlabel+'</a>'+menudiv1);
              $('#bread_continent_item').show();
              $('#bread_continent_item').next().show();
              
              $('#bread_country_item').html('<a href="javascript:;" onclick="MLS.destinations.flashNav(\''+continentid+'\', \''+countryid+'\');MLS.destinations.switchView(\''+continentid+'\', \''+continentlabel+'\',\''+countryid+'\',\''+countrylabel+'\')"><span class="current">'+countrylabel+'</span></a>'+menudiv2);
              $('#bread_country_item').show();  

              //update quicknav
              $('#country_select').selectOptionsById(continentid+'|'+continentlabel+'|'+countryid+'|'+countrylabel);

              $('.ajax').css('visibility','hidden');
            });
          }
        });
      }

      //show hidden sidebox
      if($('#mls_boxes').css('width') == "0px") {
        $('#mls_boxes').animate({width: "252px"}, 500);
      }
    }
    else {
      //change back to default breadcrumb
    
      $('#bread_country_item').hide();
      $('#bread_continent_item').next().hide();
      $('#bread_continent_item').hide();
      $('#bread_destination_item').next().hide();
        
      //change back to default side menu
      $('#mls_boxes').animate({width: "0px"}, 500);
      $('.ajax').css('visibility','hidden');
    }
  },

  //controller event for selecting a destination via quick view
  selectLand: function(select) {
    var selected=select.options[select.selectedIndex];
    if(selected.id != "-1") {
      var lands = selected.id.split("|");
      if(lands.length >= 2) {
        var continentid = lands[0];
        var continentlabel = lands[1];
        
        if(lands.length == 4) {
          var countryid = lands[2];
          var countrylabel = lands[3];
          this.switchView(continentid, continentlabel, countryid, countrylabel);
          this.flashNav(continentid, countryid);
        }
        else {
          this.switchView(continentid, continentlabel);
          this.flashNav(continentid);
        }
      }    
    }
    else {
      this.switchView();
      this.flashNav('destinations');
    }
  },
  
  showQuickNav: function() {
    $('.quicknav').fadeIn();
  },
  
  //retrieve a flash movie object 
  thisMovie: function(movieName) {
    if ( window.frames.length < 1 ) {
        return parent.document[movieName];
    }
    else {
        return window.document[movieName];
    }
  },

  //navigate within flash
  flashNav: function(continentid, countryid) {
    if(this.isFlashLoaded) {
      this.thisMovie("destinations").flashNav(continentid, countryid);
    }
  },
  
  //called by flash when flash is ready to accept commands
  flashLoaded: function() {
    this.isFlashLoaded = true;
	var a = location.hash.substring(1).split('_');
	var contid, coid, contlbl, colbl;
	if ( a.length > 1 ) {
		this.hadHash = true;
		contid = a[0];
		contlbl = a[1].replace("%20", " ");
		if ( a.length > 2 ) {
			coid = a[2];
			colbl = a[3].replace("%20", " ");
			this.switchView(contid, contlbl, coid, colbl);
			this.flashNav(contid, coid);
		}
		else {
			this.switchView(contid, contlbl);
			this.flashNav(contid);
		}
	}
    this.showQuickNav();
  }
};

//initiate page
$(document).ready(function(){

  if ( window.frames.length < 1 ) {
    $ = parent.jQuery;
  }
  else {
    $ = jQuery;
  }
  MLS.destinations.initBoxes(30, 15);
});

function switchView(continentid, continentlabel, countryid, countrylabel) {
	var contid, coid, contlbl, colbl;
	if ( ! MLS.hadHash ) {
		MLS.destinations.switchView(continentid, continentlabel, countryid, countrylabel);
	}
}


