/* 
 * Create a safe namespace for all BudgetTravel.com JS stuff
 */
String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/, '');
}

 function upperCaseFirstLetter(str) {
    str = str.slice(0,1).toUpperCase() + str.slice(1);
    return str;
 }

function Asc(String)
{
	return String.charCodeAt(0);
}

function Chr(AsciiNum)
{
	return String.fromCharCode(AsciiNum);
} 


function getLeadingHtml (input, maxChars) {
	// token matches a word, tag, or special character
	var	token = /\w+|[^\w<]|<(\/)?(\w+)[^>]*(\/)?>|</g,
		selfClosingTag = /^(?:[hb]r|img)$/i,
		output = "",
		charCount = 0,
		openTags = [],
		match;

	// Set the default for the max number of characters
	// (only counts characters outside of HTML tags)
	maxChars = maxChars || 250;

	while ((charCount < maxChars) && (match = token.exec(input))) {
		// If this is an HTML tag
		if (match[2]) {
			output += match[0];
			// If this is not a self-closing tag
			if (!(match[3] || selfClosingTag.test(match[2]))) {
				// If this is a closing tag
				if (match[1]) openTags.pop();
				else openTags.push(match[2]);
			}
		} else {
			charCount += match[0].length;
			if (charCount <= maxChars) output += match[0];
		}
	}

	// Close any tags which were left open
	var i = openTags.length;
	while (i--) output += "</" + openTags[i] + ">";
	
	return output;
};

function getLeadingHtmlCount (input, maxChars) {
	// token matches a word, tag, or special character
	var	token = /\w+|[^\w<]|<(\/)?(\w+)[^>]*(\/)?>|</g,
		selfClosingTag = /^(?:[hb]r|img)$/i,
		output = "",
		charCount = 0,
		openTags = [],
		match;

	// Set the default for the max number of characters
	// (only counts characters outside of HTML tags)
	maxChars = maxChars || 250;

	while ((charCount < maxChars) && (match = token.exec(input))) {
		// If this is an HTML tag
		if (match[2]) {
			output += match[0];
			// If this is not a self-closing tag
			if (!(match[3] || selfClosingTag.test(match[2]))) {
				// If this is a closing tag
				if (match[1]) openTags.pop();
				else openTags.push(match[2]);
			}
		} else {
			charCount += match[0].length;
			if (charCount <= maxChars) output += match[0];
		}
	}

	// Close any tags which were left open
	var i = openTags.length;
	while (i--) output += "</" + openTags[i] + ">";
	
//	alert(charCount);
	return charCount;
};

/*** function from live site that needs to keep/replace ***/
function parentCheck(passedURL) {
	// This tests that it can find the parent. If not, it will open a new window.
	if (window.opener) {
		window.opener.location = passedURL;
		window.opener.focus();
	}
	else {
		window.open(passedURL);
	}
}

// Begin launcher script for slide shows (added by A. Falcone 11/18/08)
function launchSlideshowV2 (whichShow,whichSlide) {
	
	if ( jQuery("#article-inset-right .slideshow a").length > 0 ) {
		var slideshowURL = jQuery("#article-inset-right .slideshow a").attr("href") + "?jumpToPic=" + whichSlide;
	} else {
		if (!whichSlide) {
			whichSlide = 0;
		}	
		var slideshowURL = "http://www.budgettravel.com/bt-srv/gallery/" + whichShow + "/index.html?jumpToPic=" + whichSlide;	
	}
	window.location = slideshowURL;	
}

function popunder() {
	pu = window.open("/popunder/", "popunder", "width=720,height=300,menubar=0,toolbar=0,resizable=0");
	pu.blur();
	window.focus();
}	

/* pop-up script for photo pop-ups, like on article pages */
function popitup(url, height, width)

{
	var dimString = "height=" + height + ",width=" + width + "'"
	newwindow=window.open(url,'name',dimString);
	if (window.focus)
	{
		newwindow.focus()
	}
	return false;
}
/* end pop-up script for photo pop-ups, like on article pages */

//For checking length of the comments

function textCounter(field, maxlimit) {

if (field.value.length > maxlimit)

	field.value = field.value.substring(0, maxlimit);

else 

	document.getElementById('remText').innerHTML = maxlimit - field.value.length;

}


function selectTab($target)

{

	// Tabs must be in <ul> or <ol> tags

	// Each tab must be within an <li>, but can also be nested in a deeper tag

	// example: <li><a href="#foo">Tab</a></li>



	var $tab;



	if (!$target.is('li'))

		$tab = $target.parents('li');

	else

		$tab = $target;



	$tab.siblings('li.selected').removeClass('selected').addClass('unselected');

	$tab.removeClass('unselected').addClass('selected');

}
/*** end live site functions ***/


function trimAll(sString,toTrim)
{
	if(typeof sString == 'undefined' || !sString) return '';

	while (sString.substring(0,1) == toTrim)
	{
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == toTrim)
	{
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}

jQuery.fn.serializeObject = function() {
    var o = {};
    var a = this.serializeArray();
    jQuery.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

jQuery.fn.copyCSS = function(style, toNode){
	var self = jQuery(this);
	
	if (!jQuery.isArray(style)) 
		style = style.split(' ');
	
	jQuery.each(style, function(i, name){
		toNode.css(name, self.css(name));
	});
	
	return self;
}


function sortbyVol (a,b) { 
	if ( (b[0] - a[0]) == 0) { 
		return a[1] > b[1];
	} 
	else {
		return b[0] - a[0]; 
	}
 }

function updateRealDealsMod(Howdisplay) {
    if (typeof(BTRAV.dynData) != "undefined" && typeof(BTRAV.dynData.published_deals) != "undefined") {
        var realDealModHTML = "";
        for (var i=0; i < BTRAV.dynData.published_deals.length; i=i+3) {
        if (i ==0){ 
           realDealModHTML += '<li class="active"><div class="feature first">'; 
        } else if ( (i+3) >= BTRAV.dynData.published_deals.length) {
            realDealModHTML += '<li><div class="feature last">';
            realDealModHTML +='<a href="#" class="prev btn"><img src="http://www.budgettravel.com/site_media/img/deal-module-arrow-left.png"  /></a>';              
        }
        else {
            realDealModHTML +='<li><div class="feature">';
            realDealModHTML +='<a href="#" class="prev btn"><img src="http://www.budgettravel.com/site_media/img/deal-module-arrow-left.png"  /></a>';        
        }
        
        realDealModHTML +='<a href="http://www.budgettravel.com/real-deals/' + BTRAV.dynData.published_deals[i].url + '"><img src="' + BTRAV.dynData.published_deals[i].thumbnail + '" class="thumb photo"/></a>';      
        realDealModHTML += '<a href="http://www.budgettravel.com/real-deals/' + BTRAV.dynData.published_deals[i].url + '" class="title">' + BTRAV.dynData.published_deals[1].headline + '</a>';

        if ( (i+3) < BTRAV.dynData.published_deals.length) {
            realDealModHTML +='<a href="#" class="next btn"><img src="http://www.budgettravel.com/site_media/img/deal-module-arrow-right.png" /></a></div>';
        }        
          realDealModHTML += '<div class="list-deals"><ul>' +
            '<li><a href="http://www.budgettravel.com/real-deals/' + BTRAV.dynData.published_deals[i+1].url + '">' + BTRAV.dynData.published_deals[i+1].headline + '</a></li>' +
            '<li><a href="http://www.budgettravel.com/real-deals/' + BTRAV.dynData.published_deals[i+2].url + '">' + BTRAV.dynData.published_deals[i+2].headline + '</a></li>' +        
          '</ul></div></li>';    
        }
        if (Howdisplay == "write") {
            document.writeln(realDealModHTML);
        } else {
            jQuery("#deals-scroller").html(realDealModHTML);
        }
        BTRAV.initDealScroller();
    }
}
 
function updateNavData(data) {
  BTRAV.dynData = data;
  var $navBar = jQuery("#nav");
  var $footerTop = jQuery("#footer-top");
  var dynDataRealDealsContinentHTML = "<ul>";
  var dynDataRealDealsLeavingFromHTML = "<ul>";
  var dynDataHotelsHTML = "<ul>";  
  var dynDataFeatureRealDealsHTML = "";        
  var dynDataRecentRealDealsHTML = "";       
  var dynDataFeatureArticleHTML = "";        
  var dynDataRecentArticlesHTML = ""; 
  
          if (BTRAV.isdefined(BTRAV.dynData.realdeals_continent)) {
              for (var i=0; i < BTRAV.dynData.realdeals_continent.length; i++) {
                  dynDataRealDealsContinentHTML += '<li><a href="http://www.budgettravel.com/real-deals/' + BTRAV.dynData.realdeals_continent[i].url + '">' + BTRAV.dynData.realdeals_continent[i].headline + '</a></li>';
              } 
              dynDataRealDealsContinentHTML += "</ul>";
              $navBar.find("li.real-deals .col-1 ul").replaceWith(dynDataRealDealsContinentHTML);    
          }
          
          if (BTRAV.isdefined(BTRAV.dynData.realdeals_gatewaycity)) {
              for (var i=0; i < BTRAV.dynData.realdeals_gatewaycity.length; i++) {
                  dynDataRealDealsLeavingFromHTML += '<li><a href="http://www.budgettravel.com/real-deals/' + BTRAV.dynData.realdeals_gatewaycity[i].url + '">' + BTRAV.dynData.realdeals_gatewaycity[i].headline + '</a></li>';
                  if ( Math.ceil(BTRAV.dynData.realdeals_gatewaycity.length / 2) == i) { 
                      dynDataRealDealsLeavingFromHTML += '</ul> <ul>';
                  }																					
              }
              dynDataRealDealsLeavingFromHTML += "</ul>";
              $navBar.find("li.real-deals .col-2 ul").replaceWith(dynDataRealDealsLeavingFromHTML);
          }
          if (BTRAV.isdefined(BTRAV.dynData.hotelarticles)) {
              for (var i=0; i < BTRAV.dynData.hotelarticles.length; i++) {
                  dynDataHotelsHTML += '<li><a href="http://www.budgettravel.com/' + BTRAV.dynData.hotelarticles[i].url + '">' + BTRAV.dynData.hotelarticles[i].headline + '</a></li>';
              }
              dynDataHotelsHTML += "</ul>";
              $navBar.find("li.hotels .col-1 ul").replaceWith(dynDataHotelsHTML);
          }                    
      
      if (typeof(BTRAV.dynData.featuredeal) != "undefined") {
          dynDataFeatureRealDealsHTML += '<a href="http://www.budgettravel.com' + BTRAV.dynData.featuredeal.url + '"><img src="' +  BTRAV.dynData.featuredeal.imgsource + '" class="thumb photo"/></a>';
          dynDataFeatureRealDealsHTML += '<h4 class="title"><a href="http://www.budgettravel.com' + BTRAV.dynData.featuredeal.url + '">' + BTRAV.dynData.featuredeal.headline + '</a></h4>';
          dynDataFeatureRealDealsHTML += '<p>' + BTRAV.dynData.featuredeal.dek + '</p>';			
          $footerTop.find(".realdeals .feature").html(dynDataFeatureRealDealsHTML);
      }
              
  if (typeof(BTRAV.dynData.deals) != "undefined") {
      for (var i=0; i < BTRAV.dynData.deals.length; i++) {
          dynDataRecentRealDealsHTML += '<li><a href="http://www.budgettravel.com' + BTRAV.dynData.deals[i].url + '">' + BTRAV.dynData.deals[i].headline + '</a></li>';
      }    
      $footerTop.find(".realdeals ul.link-list").html(dynDataRecentRealDealsHTML)                
  }
  
      if (typeof(BTRAV.dynData.featurerecentarticle) != "undefined") {
          dynDataFeatureArticleHTML += '<a href="http://www.budgettravel.com' + BTRAV.dynData.featurerecentarticle.url + '"><img src="' +  BTRAV.dynData.featurerecentarticle.imgsource + '" class="thumb photo"/></a>';
          dynDataFeatureArticleHTML +='<h4 class="title"><a href="http://www.budgettravel.com' + BTRAV.dynData.featurerecentarticle.url + '">' + BTRAV.dynData.featurerecentarticle.headline + '</a></h4>';
          dynDataFeatureArticleHTML +='<p>' + BTRAV.dynData.featurerecentarticle.dek + '</p>';	
          $footerTop.find(".mostrecent .feature").html(dynDataFeatureArticleHTML)                          
      }
      
      
      
      if (typeof(BTRAV.dynData.recentarticles) != "undefined") {
          for (var i=0; i < BTRAV.dynData.recentarticles.length; i++) {
             dynDataRecentArticlesHTML += '<li><a href="http://www.budgettravel.com' + BTRAV.dynData.recentarticles[i].url + '">' + BTRAV.dynData.recentarticles[i].headline + '</a></li>';
          }    
          $footerTop.find(".mostrecent ul.link-list").html(dynDataRecentArticlesHTML)                      
      }
   
     /*** update real deals mod for wrapper **/
    updateRealDealsMod("update");
}      

        	
function userData(data) {           	  	
     if (typeof(data.user) != "undefined" && typeof(data.user.username) != "undefined" && data.user.username != '') {
        var curSessionId = BTRAV.readCookie('sessionid');						 
        BTRAV.writeCookie('user' + curSessionId,data.user.username, 30);					 
        BTRAV.writeCookie('st' + curSessionId,data.user.st, 30);
        BTRAV.writeCookie('tid' + curSessionId,data.user.tid, 30);
        BTRAV.user = data.user;					
        BTRAV.update_user_nav(BTRAV.user);            
     } else {
		var curSessionId = BTRAV.readCookie('sessionid');						 
		BTRAV.writeCookie('user' + curSessionId,"", 30);					 
		BTRAV.writeCookie('st' + curSessionId,"", 30);
		BTRAV.writeCookie('tid' + curSessionId,"", 30);
	 }   
}



function tabControl(currentLink, $parent, $tabs) {
	$this = jQuery(currentLink);
	$parent.removeClass("active");
	$this.parent("li").addClass("active");
	if ($this.attr("href").indexOf("#") > 0 ){
		var tabId = $this.attr("href").substr($this.attr("href").indexOf("#"),$this.attr("href").length - $this.attr("href").indexOf("#") );
		var $selectedTab = jQuery(tabId);
	} else {
		var $selectedTab = jQuery($this.attr("href"));			
	}
	if ( !($selectedTab.hasClass("active")) ) {
		$tabs.removeClass("active").addClass("inactive");
		$selectedTab.removeClass("inactive").addClass("active");
	}		
}

function loadReaderMediaAjax(ajaxURL, jDataId) {
	jQuery.ajax({		   
		url: ajaxURL,
		dataType: 'json',
		success: function(jsonData) {
			var rrHTML = "";
			for (i=0; i < jsonData.length; i++) {	
				rrHTML += '<li class="item' + i + '"><a href="' + jsonData[i].values["link"] + '" class="photo"><span style="background: url(' + jsonData[i].values["media:thumbnail"] + ') no-repeat scroll center center;" class="imgSpan"></span></a>';
				rrHTML += '<h4><a href="' + jsonData[i].values["link"] + '">' + jsonData[i].values["title"] + '</a></h4>';
				rrHTML += '<cite class="member">By <a href="' + jsonData[i].values["ka:uploadedByUrl"] + '">' + jsonData[i].values["dc:creator"].substring(0,12) + '</a></cite></li>';
			}
			jQuery(jDataId).html(rrHTML);				
		}
	});
	
}

function initReaderMedia_RightRail() {
	var $reader_media = jQuery("#reader-media");	
	
	if (typeof(BTRAV.searchTag) != "undefined" &&  BTRAV.searchTag.trim() != "") {	
		$reader_media.find("span.citytag").html(BTRAV.searchTag);
		$reader_media.find("li a.citytag").each(function() {
			jQuery(this).attr("href",jQuery(this).attr("href") + BTRAV.searchTag);
		});
	} else {
		$reader_media.find("#reader-photos li a.citytag").html('See the most recent photos from our readers');
		$reader_media.find("#reader-videos li a.citytag").html('See the most recent videos from our readers');
		$reader_media.find("#reader-journals li a.citytag").html('See the most recent travel journals from our readers');		
		$reader_media.find("span.importantmsg").html('To show up on relevant pages, tag your photos');		
	}
	
	BTRAV.reader_media_li = jQuery("#reader-media .tab-nav li");	
	BTRAV.reader_media_tab_content = jQuery("#reader-photos, #reader-videos, #reader-journals");
	$reader_media.find(".tab-nav li a").click(function(e) {
		e.preventDefault();
		tabControl(this,BTRAV.reader_media_li,BTRAV.reader_media_tab_content);
	});		
	
	if ( typeof(BTRAV.reader_media_tabs_rr) != "undefined") {
      // photos, videos, journals
	  if (BTRAV.reader_media_tabs_rr[2] == "False") { $reader_media.find(".tab-nav li.journals").remove();}	  	  
	  if (BTRAV.reader_media_tabs_rr[1] == "False") { $reader_media.find(".tab-nav li.videos").remove(); }
	  if (BTRAV.reader_media_tabs_rr[0] == "False") { 
	  	$reader_media.find(".tab-nav li.photos").remove(); 
		jQuery("#reader-media").find(".tab-nav li").eq(0).find("a").click(); 
	  }	  
	}
	
	if (typeof(BTRAV.user) == "undefined" || BTRAV.user.username == "") {        
		$reader_media.find("a.button").click(function(e) {            
			e.preventDefault();
			BTRAV.writeCookie('backLink',jQuery(this).attr("href"), 2);
			BTRAV.writeCookie('backLinkHeadline',jQuery(this).text(), 2);     
			document.location.href = '/users/login/';
		});        
	}
}

function vpWidth() {
    return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
}

function vpHeight() {
    return window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
}

var closeModal = function() { jQuery.modal.close(); }

var BTRAV = {
	// Unescapes entified HTML 
	// "&gt;" --> ">"
	// NOT the same thing as native unescape() function
	spammers_id : [],  
    tDay: new Date(),    
    updateRegisterLoginInfo: 'yes',
	unescapeHtml:  function (str) {
		var temp = document.createElement("div");
		temp.innerHTML = str;
		var result = temp.childNodes[0].nodeValue;
		temp.removeChild(temp.firstChild)
		return result;
	},
    validEmail: function(elementValue){
       var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
       return emailPattern.test(elementValue);
     },
	
	stringIsEmpty: function(str) {
		return  !/\S/.test(str) || str.length == 0 ;
	},
	// parseUri 1.2.2
	// (c) Steven Levithan <stevenlevithan.com>
	// http://blog.stevenlevithan.com/archives/parseuri
	// MIT License
	parseUri: function(str) {
		var options = {
			strictMode: false,
			key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
			q:   {
				name:   "queryKey",
				parser: /(?:^|&)([^&=]*)=?([^&]*)/g
			},
			parser: {
				strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
				loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
			}
		};
		
		var	o   = options,
			m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
			uri = {},
			i   = 14;
	
		while (i--) uri[o.key[i]] = m[i] || "";
	
		uri[o.q.name] = {};
		uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
			if ($1) uri[o.q.name][$1] = $2;
		});
	
		return uri;
	},
	
	log: function(msg) {
		// Log to js console if it exists
		if (typeof(console) != 'undefined')
			console.log(msg);
	},
	
	  cacheBust: function(url) {
		  var n = Math.floor(Math.random()*10e6);		  
		  if (url) {
			  (url.indexOf('?') >= 0 ) ? url += '&cachebust=' + n : url += '?cachebust=' + n;	
			  return url;
		  } else {
			  return n;
		  }
	  },
  	  relativePath : function() {
		if ( location.href.indexOf("newsweek.") >=0 || location.href.indexOf("mybt.") >=0  ) {
			return 'http://www.budgettravel.com';			
		} else {
			return '';
		}
	  },	  
	  writeCookie: function(name,value,minutes) {
		  var date;
		  var expires;
		  if (minutes) {
			  date = new Date();
			  date.setTime(date.getTime() + (minutes*60*1000));
			  expires = "; expires=" + date.toGMTString();
		  }
		  else var expires = "";
		  document.cookie = name + "=" + value + "; domain=.budgettravel.com" + expires + "; path=/";
	  },
  
	  readCookie: function(name)  {
		  var nameEQ = name + "=";
		  var ca = document.cookie.split(';');
		  for(var i=0;i < ca.length;i++) {
			  var c = ca[i];
			  while (c.charAt(0)==' ') c = c.substring(1,c.length);
			  if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		  }
		  return null;
	  },
  
	  eatCookie: function(name) {
		  writeCookie(name,"",-1);
	  },
  
	  getQueryVariable: function(variable) {
		  var query = window.location.search.substring(1),
			  vars = query.split("&"),
			  i, pair;
  
		  for (i=0; i<vars.length; i++) {
			  pair = vars[i].split("=");
			  if (pair[0] == variable) {
				  return pair[1];
			  }
		  }
	  },
	updateRegisterInfo: function(what) {
        if (typeof(BTRAV.updateRegisterLoginInfo) != "undefined" && BTRAV.updateRegisterLoginInfo == 'yes') {
            if (what == 'login') {
                var $infoDiv = jQuery("#benefitsInfo");        
            } else {
                var $infoDiv = jQuery("#registerInfo");
            }
            jQuery.ajax({
               type: "GET",
               url: 'http://www.budgettravel.com/bt-srv/register/' + what + '_info.html',
               dataType: "html",
               success: function(data) {
                   $infoDiv.html(data);
               }
            });  			
            if (what == 'register') {
                if ( jQuery("#promo_opt_in").css("display") == 'none') {
                    jQuery("#promo_opt_in").remove();
                }
            }
        }
    },	

	showPopunder: function() {
        BTRAV.BTPopunderCookie = BTRAV.readCookie('BTpopunder');
        BTRAV.BTSubscriptionCookie = BTRAV.readCookie('BTSubscription');    
            if (jQuery("#ut_box").length == 0 ) { /** no UnderTone Box**/        
                var popunderURLs = ["option-b","option-c","option-d","option-e","magazine-a","magazine-b","magazine-c"];   
                var popNum = -1;
                if (BTRAV.BTPopunderCookie != "yes") {            
                    popNum = Math.floor(Math.random() * popunderURLs.length);
                    if ( popNum >= popunderURLs.length || popNum < 0) { popNum = 0;} // Not really possible but just in case
                    BTRAV.writeCookie('BTpopunder','yes',1440);
                    BTRAV.writeCookie('BTSubscription','yes',1440);
                } else if (BTRAV.BTSubscriptionCookie != "yes" ) {
                    popNum = Math.floor(Math.random() * 3) + 4;
                    BTRAV.writeCookie('BTSubscription','yes',1440);            
                }
                
                if ( popNum >= 0 ) {
                    BTRAV.writeCookie("popunderTimer","yes",1440);                  
                    var openURL = 'http://www.budgettravel.com/bt-srv/popunder/' + popunderURLs[popNum] + '.html';        
                    if (typeof(jQuery.modal) != "undefined" && typeof(screen) != "undefined" && vpWidth() > 725 && vpHeight() > 425 && jQuery("#ut_box").length < 1){
                        openURL = openURL + '?popupType=Overlay';
                        jQuery.modal('<iframe src="' + openURL + '" height="401" width="717" id="newslettersignupFrame" frameborder="0" scrolling="no" >', {containerCss: { height: 401, width: 717 }});
                    } else {
                        /***openURL = openURL + '?popupType=Overlay';
                        jQuery.modal('<iframe src="' + openURL + '" height="401" width="717" id="newslettersignupFrame" frameborder="0" scrolling="no" >', {containerCss: { height: 401, width: 717,  overlayClose: true }});
                        ***/ 
                       openURL = openURL + '?popupType=Popup';
                        var BTpopunder = window.open(openURL, "BTpopunder", "width=717,height=401,menubar=0,toolbar=0,resizable=0,scrollbars=0");
                        if (BTpopunder == null || typeof(BTpopunder)=='undefined') {
                            jQuery.modal('<iframe src="' + jQuery(this).attr("href") + '" height="401" width="717" id="newslettersignupFrame" frameborder="0" scrolling="no" >');                 
                        } else if (typeof(BTpopunder.top.parent.opener) != "undefined" && BTpopunder.top.parent.opener != null) {
                            BTpopunder.top.parent.opener.focus();
                        }                 
                    }
                }
            }
        
    },
	
	update_user_nav : function(data) {
	  var login_div = jQuery("#loginInfo");
	  if (login_div.children().is("span.username")) {
			return false;
		}	  
	  if (typeof(data.username) != "undefined" && data.username != "") {
			  BTRAV.user = data;
			  login_div.html(
				  "<span class=\"username\">You are logged in as "
					  + "<a class=\"bold\" href=\"" + BTRAV.relativePath() + "/users/login/\">"
					  + data.username
					  + "</a></span>"
					  + "<a class=\"logout\" href=\"" + BTRAV.relativePath() + "/users/logout/\">LOG OUT</a>"
			  );
			BTRAV.kainfo = '&st=' + data.st + '&tid=' + data.tid;				
            jQuery(document).ready(function() {               
			  jQuery("#myBTNav a[href*='as=21864'], #reader-media .button").each(function() {					
				  jQuery(this).attr('href',jQuery(this).attr('href') + BTRAV.kainfo );
			  })
            });
		  }
	},
    
	checkUserCookie: function() {
		var curSessionId = BTRAV.readCookie('sessionid');
		var usercookie = {};
			usercookie = {
			'username' : BTRAV.readCookie('user' + curSessionId),
			'st' : BTRAV.readCookie('st' + curSessionId),
			'tid' : BTRAV.readCookie('tid' + curSessionId)
		} 		
		if (usercookie.username != null) {
			BTRAV.update_user_nav(usercookie);
			return true;
		} else {
			return false;
		}
	},
	
	update_user_login : function () {		
		if (!BTRAV.checkUserCookie()) {
			var ajaxurl = BTRAV.relativePath() + '/users/login/';
			jQuery.ajax({
			   type: "GET",
			   url: ajaxurl,
			   dataType: "jsonp",
			   jsonpCallback: "userData"
			});  			
		}
	},
	
	isdefined: function( variable)
		{
			return (typeof(variable) == "undefined")?  false: true;
		},
		
	callOmniture: function(extrapageName) {
        if (location.href.indexOf("qa.") < 0 && location.href.indexOf("qaadmin.") < 0) {        
            if (typeof(s) != "undefined") {
                s.referrer = document.referrer;
                s.visit_referrer = document.referrer;
                s.events = "";
                void(s.t());
            }
            
            if (typeof(_gaq) != "undefined"){
                if (extrapageName != "") {                    
                    if (location.href.indexOf('src=') >=0 ) {
                        var trackPhotoNum = location.pathname + extrapageName + location.search.replace("?","&");
                    } else {
                        var trackPhotoNum = location.pathname + extrapageName;
                    }                    
                } else {
                    if (location.href.indexOf('src=') >=0 ) {
                        var trackPhotoNum = location.pathname + location.search;
                    } else {
                        var trackPhotoNum = location.pathname;
                    }  
                }
                
                _gaq.push(['_setAccount', 'UA-23042849-1']);
                _gaq.push(['_trackPageview', trackPhotoNum]);              
            }        
            
        }
	},	
    
	isInArray : function(searchVal,searchArray) {
		var index = 0;
		while (index < searchArray.length)
		{
		  if (searchArray[index].toLowerCase() == searchVal.toLowerCase()) { 
		  	index = searchArray.length; 		  
			return true;
		  } else { 
		  	index++;
		  }
		}
		return false;		
	},
	debug: function(msg) {
		// Check for 'jsdebug' in query string and log to console if it's there
		if (window.location.search.match(/jsdebug/))
			BTRAV.log(msg);
	}
	
	
}

BTRAV.addCommentBox = function($appendObj, bubbleheadText, articleId, commentPageType,commentType,commentsAjax ) {
     /*** need to move to a different function **/
    if (location.href.indexOf('dev.') < 0 && articleId == 7 && commentPageType == 'Contest') {
        jQuery("#finalist .photo img").each(function() {   
           if (jQuery(this).attr("src") == 'http://images.budgettravel.com/1108covercontestphoto-8162011_vert-medium.jpeg') {           
                jQuery(this).attr("src","").attr("src",'http://www.budgettravel.com/bt-srv/images/magcovercontest/11_NOV_CoverPHOTO_181X238.jpg').show();                
                var $lageImage1 = jQuery('<img src="http://www.budgettravel.com/bt-srv/images/magcovercontest/11_NOV_CoverPHOTO_large.jpg" />');
                jQuery(this).click(function() {
                    $lageImage1.modal( {overlayClose:true, minWidth:400, minHeight: 525});
                });
           } else if (jQuery(this).attr("src") == 'http://images.budgettravel.com/110816covercontestillo-8162011_vert-medium.jpeg') {             
                jQuery(this).attr("src","").attr("src",'http://www.budgettravel.com/bt-srv/images/magcovercontest/11_NOV_CoverILLO_181X238.jpg').show();
                var $lageImage2 = jQuery('<img src="http://www.budgettravel.com/bt-srv/images/magcovercontest/11_NOV_CoverILLO_large.jpg" />');
                jQuery(this).click(function() {
                    $lageImage2.modal( {overlayClose:true, minWidth:400, minHeight: 525});
                });
           } else if (jQuery(this).attr("src") == 'http://images.budgettravel.com/bang-pa-in-8172011_vert-small.jpeg') {             
                jQuery(this).attr("src","").attr("src",'http://www.budgettravel.com/bt-srv/images/magcovercontest/11_NOV_CoverRIBBON_181X238.jpg').show();
                var $lageImage3 = jQuery('<img src="http://www.budgettravel.com/bt-srv/images/magcovercontest/11_NOV_CoverRIBBON_large.jpg" />');
                jQuery(this).click(function() {
                    $lageImage3.modal( {overlayClose:true, minWidth:400, minHeight: 525});
                });
           }
        });
    }
    
    if (location.href.indexOf('dev.') < 0) {
        var contestcommentsdiv="";
            contestcommentsdiv += "<div id=\"allowComments\">    ";
            contestcommentsdiv += "    <h2 class=\"bubble-head\">" + bubbleheadText + "<\/h2>";
            contestcommentsdiv += "    <p id=\"comments_errors\"><span>Please log in to post comments<\/span><\/p>";
            contestcommentsdiv += "    <p id=\"comments_msg\"><\/p>          ";
            contestcommentsdiv += "    <div id=\"articleSubmitComments\" class=\"clearfix\">";
            contestcommentsdiv += "        <p class=\"add_comment\">Comment on this contest <span id=\"sign_reg\"><\/span><\/p>";
            contestcommentsdiv += "        <form action=\"#\" name=\"addcomments\" id=\"addcomments\" method=\"post\">";
            contestcommentsdiv += "        <textarea id=\"commentBox\" name=\"comment\" class=\"add_comment\" onfocus=\"javascript:BTRAV.comments.checkCommentLogin();\" wrap=\"soft\" onkeydown=\"textCounter(this, 5000);\" onkeyup=\"textCounter(this, 5000);\"><\/textarea>";
            contestcommentsdiv += "        <input type=\"submit\" class=\"button submit_button\" value=\"Submit\" \/>";
            contestcommentsdiv += "        <span class=\"limit_chars\">(Limit 5000 characters \/ <span id=\"remText\">5000<\/span> characters remaining)<\/span>";
            contestcommentsdiv += "        <\/form>";
            contestcommentsdiv += "    <\/div>";
            contestcommentsdiv += "    <div id=\"comments\">";
            contestcommentsdiv += "        <p class=\"number_comments\">";
            contestcommentsdiv += "            <span id=\"noOfComments\"><\/span>";
            contestcommentsdiv += "        <\/p>";
            contestcommentsdiv += "    <\/div>";
            contestcommentsdiv += "<\/div> ";
        
        if ($appendObj == "") { document.write(contestcommentsdiv); } else { $appendObj.append(contestcommentsdiv); }
        
        if (typeof(BTRAV.user)!= "undefined"  && typeof(BTRAV.user.username) != "undefined" && BTRAV.user.username != "") {                       
        } else {
            jQuery("#sign_reg").html('(<a href="/users/login/">Log In</a> or <a href="/users/register/">Register</a>)');
        }
        
        BTRAV.commentsAjax = commentsAjax;
        BTRAV.commentPageType = commentPageType.toLowerCase();        
        BTRAV.commentType = (commentType!= "" ) ?  commentType :"comment";   
        jQuery("#addcomments").submit(function(e) {
            e.preventDefault();
            BTRAV.comments.submitComment(articleId);
        });    
        BTRAV.comments.kaComments(articleId,1);
    }    
}


/*** article js ***/
BTRAV.article = {	
	enlagePopupable: function() {
		jQuery("a.enlargePopupable").click(function(e) {
			e.preventDefault();
				jQuery.get(jQuery(this).attr("href"),function(data){ 												
					jQuery('<div id="popupableoverlay" class="popupableoverlay"></div>').html(data).modal( {overlayClose:true, minWidth:620, maxWidth:620, minHeight: 455, 
											onOpen: function (dialog) {
												dialog.overlay.fadeIn(300, function () {
													dialog.container.slideDown(300, function () {
														dialog.data.fadeIn(300);
													});
												}); 
											}
										});
				});					
		});
	},
	rearrangeImage : function() {	
		if (jQuery("#photo-panoramic").length > 0) {	
			if (jQuery("#photo-top-right").length > 0 ) {				
				jQuery("#photo-top-right").prependTo(jQuery("#content-body>p:eq(1)")); 
			}
			if (jQuery("#photo-top-left").length > 0 ) {		
				jQuery("#photo-top-left").prependTo(jQuery("#content-body>p:eq(1)"));			
			}
		}
	},
	
	placeInset : function() {
        var $articleInset = jQuery("#article-inset-right");
        if ( $articleInset.length > 0 && $articleInset.html().trim().length > 50) {
            var $contentBodyP = jQuery("#content-body>p");
		  if ($contentBodyP.eq(0).html().length > 800 ) {
			  $contentBodyP.eq(0).after($articleInset.css("display","block"));
		  } else {
			  $contentBodyP.eq(1).after($articleInset.css("display","block"));
		  }
    	}
	}
}


/** comment js ***/
BTRAV.comments = {
    editorsList: 'jessholl,laura.buckley,LauraMichonski,Sean',
    initedCommentType: 0,
    updateCommentType: function(){
        /** Tool comment Type **/
        if (typeof (articleId) != "undefined" && articleId == '7593') {            
            var $allowComments = jQuery("#allowComments");
            BTRAV.commentPageType = "tool"; 
            $allowComments.find(".rate_article span").html("Rate this Tool");
            $allowComments.find("h2.bubble-head").html("Tool Comments")
            $allowComments.find("p.add_comment").html("Comment on this Tool")
            
        }
    },
	checkCommentLogin : function() {
		if (typeof(BTRAV.user)!= "undefined"  && typeof(BTRAV.user.username) != "undefined" && BTRAV.user.username != "") {
			jQuery("#commentBox").removeAttr("disabled");
			jQuery("#comments_errors").hide();			
			jQuery("#sign_reg").hide();
			return true;
		} else {
			jQuery("#commentBox").attr("disabled","disabled");
			jQuery("#comments_errors").show();
			jQuery("#sign_reg").show();
			return false;
		}
	},
    
	kaComments: function(articleId, page_num) {	
            if (BTRAV.comments.initedCommentType == 0 ) {
                BTRAV.comments.initedCommentType = 1;
                BTRAV.comments.updateCommentType();                             
            }
            var comment_div = jQuery("#comments");
            if (typeof(BTRAV.commentsAjax) != "undefined" && BTRAV.commentsAjax != "") {
                var ka_url = '/kickapps/comments/ajax/' + BTRAV.commentsAjax + '/' + articleId + '/';				
            } else {
                var ka_url = '/kickapps/comments/ajax/editorial.articlebase/' + articleId + '/';		
            }
            if (typeof(page_num) != "undefined" && page_num > 1 ) {
                var ka_url_paged = ka_url + '?page=' + page_num;
            } else {
                var ka_url_paged = ka_url
            }
            jQuery.getJSON(BTRAV.cacheBust(ka_url_paged), function(data) {
                if (typeof(BTRAV.commentPageType) == "undefined") {
                    BTRAV.commentPageType = "article";
                }
                if (typeof(BTRAV.commentType) == "undefined") {
                    BTRAV.commentType = "comment";
                }
                
                if (typeof(data.average_rating) != "undefined" && parseFloat(data.average_rating) > 0) {jQuery("#overAllRating").html(data.average_rating);}
                
                jQuery("#comments .seemorecomments").remove();	
                if ( typeof(data.comments) != "undefined" && typeof(data.total) != "undefined" && data.total > 0 ) {			
                    var totalComments = 0;
                    if (typeof( data.total) != "undefined") { totalComments = data.total; }
                    (totalComments > 1) ? commentText=' '+ BTRAV.commentType + 's' : commentText=' ' + BTRAV.commentType;
                    jQuery("#noOfComments").html('This ' + BTRAV.commentPageType + ' has ' +  totalComments + commentText);
                    jQuery("#commentsbar").html('<a href="#allowComments">' + BTRAV.commentType + 's (' + totalComments + ')</a>');
                    jQuery.each(data.comments, function() {
                        if (!BTRAV.isInArray(this.author_kickapps_id, BTRAV.spammers_id)) {
                            if (BTRAV.comments.editorsList.indexOf(this.author_username) >= 0 ) { 
                                var postedbyWho = '<p class="postedby editor">';
                            } else {
                                var postedbyWho = '<p class="postedby">';
                            }
                            comment_div.append(
                                "<div class=\"comment\">"
                                + postedbyWho + "Posted by <a href=\"http://mybt.budgettravel.com/"
                                + "kickapps/service/displayKickPlace.kickAction?as=21864&u="
                                + this.author_kickapps_id + "\">" + this.author_username
                                + "</a> on " + this.created + "</p>"
                                + "<p class=\"body-text\">" + this.body + "</p></div>"
                            );
                        }
                    });
                    var displayedComments =  jQuery("#comments .comment").length;
                    if ( displayedComments < totalComments) {					
                        page_num++;
                        var next10comments = 10;					
                        if ( (totalComments - displayedComments) < 10)  {  
                            next10comments = totalComments - displayedComments; 
                        }
                       ( next10comments > 1) ? commentString = next10comments + " " + BTRAV.commentType + 's' : commentString = next10comments + " " + BTRAV.commentType;
                        comment_div.append('<a href="javascript:BTRAV.comments.kaComments(' + articleId + ',' + page_num + ')" class="teal bold seemorecomments">view next ' + commentString + '</a>');
                    }
                } else {
                    jQuery("#noOfComments").html('This ' + BTRAV.commentPageType + ' has 0 ' + BTRAV.commentType + 's');
                    jQuery("#commentsbar").html('<a href="#allowComments">' + BTRAV.commentType + 's (0)</a>');				
                }			
            });        
	},
    
	submitRating : function(articleId,curRating) { 			
		if (BTRAV.comments.checkCommentLogin()) {
			if (typeof(BTRAV.commentsAjax) != "undefined" && BTRAV.commentsAjax != "") {
				var add_ratings_url = '/kickapps/add_rating/ajax/' + BTRAV.commentsAjax + '/' + articleId + '/';				
			} else {
				var add_ratings_url = '/kickapps/add_rating/ajax/editorial.articlebase/' + articleId + '/';	
			}	
            
			jQuery.ajax({
				type: 'POST',
				url: add_ratings_url,
				data: {'rating': curRating},
				dataType: 'html',
				success: function() {
					jQuery("#comments_msg").html("Your rating has been posted. Thank You.").addClass("success").show();					
					jQuery('.star-rating').rating('readOnly',true).unbind('click'); 		
                    if (typeof(articleId) != "undefined") {
                        if (typeof(BTRAV.commentsAjax) != "undefined" && BTRAV.commentsAjax != "") {
                            var ka_url = '/kickapps/comments/ajax/' + BTRAV.commentsAjax + '/' + articleId + '/';				
                        } else {
                            var ka_url = '/kickapps/comments/ajax/editorial.articlebase/' + articleId + '/';		
                        }
                        jQuery.getJSON(BTRAV.cacheBust(add_ratings_url), function(data) {						
                            if (typeof(data.average_rating) != "undefined" && parseFloat(data.average_rating) > 0) {jQuery("#overAllRating").html(data.average_rating);}
                        });
                    }
				},
				error: function() {
					jQuery("#comments_msg").html("You have already rated this article").show();
					jQuery('.star-rating').rating('readOnly',true).unbind('click');
				}
			})
  			
		}
	},	
	submitComment : function(articleId) {
		if (BTRAV.comments.checkCommentLogin() && jQuery("#commentBox").val().trim().length > 0 ) {
			if (typeof(BTRAV.commentType) == "undefined") {
				BTRAV.commentType = "comment";
			}			
			if (typeof(BTRAV.commentsAjax) != "undefined" && BTRAV.commentsAjax != "") {
				var add_kacomments_url = '/kickapps/add_comment/ajax/' + BTRAV.commentsAjax + '/' + articleId + '/';				
			} else {
				var add_kacomments_url = '/kickapps/add_comment/ajax/editorial.articlebase/' + articleId + '/';	
			}
			jQuery("#articleSubmitComments").hide();
			
			jQuery("#comments_msg").html("Posting your " + BTRAV.commentType + " ...").fadeIn("slow");			
			jQuery.ajax({
				type: 'POST',
				url: add_kacomments_url,
				data: jQuery("#addcomments").serialize(),
				success: function() {
					jQuery("#comments .comment").remove();
					BTRAV.comments.kaComments(articleId,1);	
					jQuery("#comments_msg").html("Your "+ BTRAV.commentType + " has been posted. Thank You.").addClass("success").show();						
				},
				error: function() {
					jQuery("#comments_msg").html("There was an error in posting your "+ BTRAV.commentType + ", please try again.").addClass("error").show();
					jQuery("#articleSubmitComments").show();					
				}
			})
		}
	}
	
	
}

/*** Blogs Nav Drop Dwon **/
BTRAV.updateBlogNavRecentPopular = function() { 
	jQuery.getScript('http://blog.budgettravel.com/budgettravel/rss/recent_popular.js',function() {				
		var navblogJustIn = '';
        if (typeof(module) != "undefined") {
            for (j=0; j<4; j++) {
                if (module[0].content[j].url != "") {
                    if (j != 3) {
                        navblogJustIn += '<li><div class="timestamp">';				
                    }
                    else {
                        navblogJustIn += '<li class="last"><div class="timestamp">'; 									
                    }
                    navblogJustIn += '' + module[0].content[j].pubday + ',' + module[0].content[j].timestamp + '</div><a href="' + module[0].content[j].url + '">' + module[0].content[j].headline + '</a></li>';
                    
                }
            }
            jQuery("#navblogJustIn").html(navblogJustIn)
        }
		
		var navTalking = '';
        if (typeof(moduleTalking) != "undefined") {        
            for (j=0; j<4; j++) {
                var totalComments = parseInt(moduleTalking[0].content[j].comments);						 				
                ( totalComments > 1) ? commentString = totalComments + " comments" : commentString = totalComments + " comment";
        
                if (moduleTalking[0].content[j].url != "") {
                    if (j != 3) {
                        navTalking += '<li><div class="timestamp">';				
                    }
                    else {
                        navTalking += '<li class="last"><div class="timestamp">'; 									
                    }				
                navTalking += '' + moduleTalking[0].content[j].pubdate + '<span class="comments">[' +  commentString +']</span></div><a href="' + moduleTalking[0].content[j].url + '">' + moduleTalking[0].content[j].headline + '</a></li>';									
                }
            }
            jQuery("#navTalking").html(navTalking)
        }        
		if (BTRAV.ads.sitename == 'budgettravel.homepage') {		
			  var blogJustIn = '';
			  for (j=0; j<4; j++) {
				  var authorName = '';
				  if (module[0].content[j].url != "") {
					  if ( (module[0].content[j].author != "Budget Travel") && (module[0].content[j].author != "Affordable Europe") ) {
						  authorName = module[0].content[j].author + ", ";
					  }
				  blogJustIn += '<li><cite class="byline">' + authorName + module[0].content[j].pubday + ', ' +  module[0].content[j].pubdate + ',' + module[0].content[j].timestamp + '</cite><h3 class="title"><a href="' + module[0].content[j].url + '">' + module[0].content[j].headline + '</a></h3><p class="blurb">' + module[0].content[j].blurb + '</p></li>';				
				  }
			  }
			  jQuery("#blogJustIn").html(blogJustIn);
		}
        
        if (location.pathname == "/") {
            jQuery("#otherBlogs a").attr("href","http://blog.budgettravel.com/budgettravel/");
        }
	});
	
	
}

	BTRAV.animateResult = function(contestEntries) {
        if (location.pathname.indexOf('thank-you') >= 0 && location.pathname.indexOf('thank-you/1') < 0) {
            document.write('</strong>');
        }
        
		for (i=0; i< contestEntries.entries.length; i++) {
			var candidateId =  "#candidate" + contestEntries.entries[i].entryId;
			var curWidth = contestEntries.entries[i].curWidth;
			jQuery(candidateId).find(".result-content").animate({width: curWidth},curWidth * 10).addClass("finished");		
		}
	}

/** facebook like **/
    BTRAV.addFBLike = function(contenturl) {
        if (contenturl == '') {
            var FBarticleURL = 'http://www.budgettravel.com' + location.pathname;
        } else {
            var FBarticleURL = 'http://www.budgettravel.com' + contenturl;
        }
                    
        document.write('<iframe scrolling="no" frameborder="0" id="BTfblike" allowtransparency="true" src="http://www.facebook.com/plugins/like.php?href=' + FBarticleURL + '&amp;layout=button_count&amp;show_faces=false&amp;width=90&amp;action=like&amp;colorscheme=light&amp;height=20&amp;ref=fblike"></iframe>');
    }
/** init readerMedia **/

BTRAV.loadReaderMedia_rr = function() {
	if (typeof(BTRAV.searchTag) == "undefined" || typeof(articleId ) == "undefined") {
		BTRAV.searchTag = '';
	}
    
    var useSearchTag = 0;    
    if (typeof(publishedDate) != "undefined") {
        var UGCactiveDate = new Date("June 15, 2011");
        var artPubDate = new Date(publishedDate);
        if (artPubDate >= UGCactiveDate)  {
            useSearchTag = 1;
        }
    }

    if ( BTRAV.searchTag == '' || useSearchTag == 0 )  { 	    
        /** Exactly one destination Tag **/
        if ( typeof(BTRAV.ads.taxa['continent']) != "undefined" && BTRAV.ads.taxa['continent'].length  < 2 && BTRAV.ads.taxa['country'].length  < 2 && BTRAV.ads.taxa['state'].length  < 2 &&  BTRAV.ads.taxa['city'].length  < 2 ) {
            if (BTRAV.ads.taxa['city'].length == 1) {
                BTRAV.searchTag = BTRAV.ads.taxa['city'][0];		
            } else if (BTRAV.ads.taxa['state'].length == 1) {
                BTRAV.searchTag = BTRAV.ads.taxa['state'][0];				
            } else if (BTRAV.ads.taxa['country'].length == 1) {
                BTRAV.searchTag = BTRAV.ads.taxa['country'][0];				
            } else if (BTRAV.ads.taxa['continent'].length == 1) {
                BTRAV.searchTag = BTRAV.ads.taxa['continent'][0];	
            }
            /*** or Exactly one Activies ***/		
        } else if ( typeof(BTRAV.ads.taxa['activities-and-interests']) != "undefined" && BTRAV.ads.taxa['activities-and-interests'].length < 2) {
                BTRAV.searchTag = BTRAV.ads.taxa['activities-and-interests'][0];		
        } else {
            /*** update to use search tag when ready **/
            BTRAV.searchTag = '';		
        }
        
        BTRAV.searchTag = BTRAV.searchTag.replace(/-/g," ").replace(" dc"," DC"); 
	}
    
	if (BTRAV.searchTag.indexOf(" ")>= 0 && BTRAV.searchTag.indexOf('"') < 0) { BTRAV.searchTag = '"' + BTRAV.searchTag + '"';} 	
	
	var readerUrlphoto= '/reader_media_feed/json/?quantity=6&sortType=recent&mediaType=photo&tags=' + BTRAV.searchTag;
	loadReaderMediaAjax(readerUrlphoto, '#reader-photos-ol');
	var readerUrlVideo = '/reader_media_feed/json/?quantity=6&sortType=recent&mediaType=video&tags=' + BTRAV.searchTag;
	loadReaderMediaAjax(readerUrlVideo, '#reader-videos-ol');		
	var readerUrlblog = '/reader_media_feed/json/?quantity=6&sortType=recent&mediaType=blog&tags=' + BTRAV.searchTag;
	loadReaderMediaAjax(readerUrlblog, '#reader-journals-ol');	 
	initReaderMedia_RightRail();	 
	jQuery("#reader_media_ajax").remove();	
	jQuery("#reader-media").show(); 	
}

function rotateDealModule() {
    var $dealscrollerActiveNext = jQuery("#deals-scroller li.active a.next");
    var $dealscrollerActivePrev = jQuery("#deals-scroller li.active a.prev");
	if ( BTRAV.rotateDealOrder == "next") {
		if ($dealscrollerActiveNext.length > 0) {
			$dealscrollerActiveNext.click();
		} else {             
			$dealscrollerActivePrev.click();			
		}
	} else {
		if ($dealscrollerActivePrev.length > 0) {
			$dealscrollerActivePrev.click();
		} else {            
			$dealscrollerActiveNext.click();
		}
	}
    clearTimeout(BTRAV.rDealtimer);
	BTRAV.rDealtimer = setTimeout("rotateDealModule()",  BTRAV.rotateTimer );
}


/** Real Deals Custom Content **/
BTRAV.initDealScroller = function() {
    BTRAV.rotateDealOrder = "next";
    BTRAV.rotateTimer = 7000;    
    var $dealscroller = jQuery("#deals-scroller");
	$dealscroller.hover(
        function(){ clearTimeout(BTRAV.rDealtimer)}, 
        function() { clearTimeout(BTRAV.rDealtimer); BTRAV.rDealtimer = setTimeout("rotateDealModule()",  BTRAV.rotateTimer ); 
    });    
    
	$dealscroller.find("a.btn").hover(function(){jQuery(this).fadeTo("fast",.5)}, function() {jQuery(this).fadeTo("fast",1)});
    
	$dealscroller.find("a.next, a.prev").click(function(e) {
		e.preventDefault();                           		
        $dealscroller.find(">li").removeClass("active");        
		if (jQuery(this).hasClass("next")) {	
            BTRAV.rotateDealOrder = "next"; 
		    var $nextActive = jQuery(this).parent().parent().next();            
		} else {			
            BTRAV.rotateDealOrder = "prev";
		    var $nextActive = jQuery(this).parent().parent().prev();            
		}
		$nextActive.addClass("active");						
		var nextLeft = $nextActive.position().left * -1;			
		$dealscroller.clearQueue().animate({left: nextLeft});              
	});

    BTRAV.rDealtimer = setTimeout("rotateDealModule()",  BTRAV.rotateTimer );          
}

/*** init Custom Content Accordion ***/
BTRAV.initCustomModule = function() {
    var $customModule = jQuery("#custom-module");    
    $customModule.find(".right-module>h3 a").click(function(e){ e.preventDefault();});
	$customModule.find(".right-module>h3").click(function() {
        var $thisParent = jQuery(this).parent();
        if (!$thisParent.hasClass("active")) {
         if ( jQuery.browser.msie &&  parseInt(jQuery.browser.version,10) <= 8.0) {
            $customModule.find(".module-content").hide().parent().removeClass("active");
            jQuery(this).siblings(".module-content").show();         
         } else {
            $customModule.find(".module-content").slideUp().parent().removeClass("active");
            jQuery(this).siblings(".module-content").slideDown();
         }
            $thisParent.addClass('active');     
            if ($thisParent.attr("id") == 'custom-module-real-deals') {
                jQuery.get('http://ad.doubleclick.net/ad/budgettravel.house;adid=7194467;sz=1x1;ord=' + Math.floor(Math.random() * 9999999999) + '?');            
            } else if ($thisParent.attr("id") == 'custom-module-booking') {
                jQuery.get('http://ad.doubleclick.net/ad/budgettravel.house;adid=7194827;sz=1x1;ord=' + Math.floor(Math.random() * 9999999999) + '?');            
            } else if ($thisParent.attr("id") == 'custom-content') {
                jQuery.get('http://ad.doubleclick.net/ad/budgettravel.house;adid=7194947;sz=1x1;ord=' + Math.floor(Math.random() * 9999999999) + '?');                  
            }
        }        
	});
           
    /** default custom content open up **/
    if ( location.pathname.indexOf('/real-deal/') >= 0 || location.pathname.indexOf('/real-deals/') >= 0 || location.pathname.indexOf('/hotels/') >= 0 || location.pathname.indexOf('/hotel/') >= 0) {
        $customModule.find("#custom-module-booking .module-content").show().parent().addClass('active');
    } else if ( location.pathname.indexOf('/destinations/') >= 0 ) {
        $customModule.find("#custom-content .module-content").show().parent().toggleClass('active');
    } else {
        if (location.pathname.indexOf('custom-content') >=0) {
            var randN = Math.floor(Math.random() * 2);
        } else {
           var randN = Math.floor(Math.random() * 3); 
           if (randN == 0) {
               if ( $customModule.find("#deals-scroller>li").length > 3) {
                    $customModule.find("#custom-module-real-deals .module-content").show().parent().addClass('active');    
               } else {
                    $customModule.find("#custom-content .module-content").show().parent().toggleClass('active');   
               }
           } else if (randN == 1) {
               $customModule.find("#custom-module-booking .module-content").show().parent().addClass('active');    
           } else {                   
               $customModule.find("#custom-content .module-content").show().parent().toggleClass('active');
           }      
        }
    }
    
    /** append src to real deals links **/
    $customModule.find("#deals-scroller a:not(.btn)").each(function() {
        jQuery(this).attr("href",jQuery(this).attr("href") + '?src=rrmod');
    });
    
    /** real deals rotator **/    
	BTRAV.initDealScroller();
}
    
/** init follow us popup **/
    BTRAV.initRssPopUp = function() {    
    jQuery("#follow-us-rss").mouseover(function() { 
            jQuery("#follow-us-rss").RemoveBubblePopup();
            jQuery("#follow-us-rss").CreateBubblePopup({
			position : 'top',
			align	 : 'center',
			innerHtml: '<ul class="feedlist"><li><a href="http://www.budgettravel.com/latest/features/feed/" target="_blank">Feature feed</a></li><li><a href="http://www.budgettravel.com/latest/real-deals/feed/" target="_blank">Real Deals feed</a></li><li><a href="http://www.budgettravel.com/latest/hotels/feed/" target="_blank">Hotel Review feed</a></li></ul>',
			themeName: 'grey', 
			themePath: 'http://www.budgettravel.com/site_media/img/jquerybubblepopup-theme', 
			selectable: true,
			alwaysVisible: false,
			openingSpeed: 100,
			closingSpeed: 100,
            afterHidden: function() { jQuery("#follow-us-rss").RemoveBubblePopup(); }            
            });
        }); 
}     

/*** init functions moved over to BTRAV.init.live.js ***/
/*** init functions ***/
BTRAV.initNav = function() {	
jQuery("#myBTNav .col-1 li").eq(4).find("a").attr("href","http://mybt.budgettravel.com/service/displayMyPlace.kickAction?as=21864");    
jQuery('#nav .menu-item').hover(function() {
		jQuery(this).find('.dropdown').show();		
	}, function() {
		jQuery(this).find('.dropdown').hide();
	});	

	jQuery(document).ready(function() {
		BTRAV.updateBlogNavRecentPopular();
	});

}

BTRAV.initBookingStrategy = function() {
	  var $bookingStrategyContentP = jQuery("#booking_strgy_content .content>p");
	  if ( $bookingStrategyContentP.length > 1) {		 		  
		  $bookingStrategyContentP.filter(":eq(0)").append('<span id="more-hellip">&hellip;</span>');
		  jQuery("#booking_strgy_content .content>p:gt(0), #strategy-author").wrapAll('<div id="strategy-more"/>');
		  jQuery("#strategy-author").append
		  jQuery("#booking_strgy_container #display-more").toggle(
			  function() {
				jQuery("#more-hellip").hide();			
				jQuery("#strategy-more").slideDown(800,function() {
					jQuery("#display-more").text("Close").removeClass("down-arrow").addClass("up-arrow");
				});
			  },
			  function() {
				jQuery("#strategy-more").slideUp(800,function() {
					jQuery("#more-hellip").show();			
					jQuery("#display-more").text("More").removeClass("up-arrow").addClass("down-arrow");				
				});
			  }
		  );
	  } else {
			jQuery("#booking_strgy_container #display-more").hide();		
	  }	
}


/** custom content Static **/
BTRAV.customContentDest = '<div class="leftcol"><div class="select" id="7935">Barcelona</div><div class="select" id="205">Belize</div><div class="select" id="9183">Boston</div><div class="select" id="9233">Chicago</div><div class="select" id="235">Costa Rica</div><div class="select" id="268">Greece</div><div class="select" id="9409">Hawaii</div><div class="select" id="289">Ireland</div><div class="select" id="292">Italy</div><div class="select" id="9466">Key West</div><div class="select" id="9504">Las Vegas</div></div><div class="leftcol"><div class="select" id="9524">Los Angeles</div><div class="select" id="9131">Maine</div><div class="select" id="9556">Miami</div><div class="select" id="9602">New Orleans</div><div class="select" id="9605">New York</div><div class="select" id="9625">Orlando</div><div class="select" id="3709">Paris</div><div class="select" id="363">Puerto Rico</div><div class="select" id="9721">San Francisco</div><div class="select" id="9739">Seattle</div><div class="select" id="9842">Washington, D.C.</div></div>'; 

BTRAV.customContentActivities = '<div class="leftcol"><div class="checkbox"><input type="checkbox" name="custom-activities" value="5"><span>Adventure</span></div><div class="checkbox"><input type="checkbox" name="custom-activities" value="7"><span>Amusement and Theme Parks</span></div><div class="checkbox"><input type="checkbox" name="custom-activities" value="9"><span>Art</span></div><div class="checkbox"><input type="checkbox" name="custom-activities" value="13"><span>Beaches</span></div><div class="checkbox"><input type="checkbox" name="custom-activities" value="139;25"><span>Cruises</span></div><div class="checkbox"><input type="checkbox" name="custom-activities" value="26"><span>Culture</span></div><div class="checkbox"><input type="checkbox" name="custom-activities" value="173"><span>Family</span></div><div class="checkbox"><input type="checkbox" name="custom-activities" value="29"><span>Festivals</span></div><div class="checkbox"><input type="checkbox" name="custom-activities" value="31"><span>Food and Drink</span></div></div><div class="leftcol"><div class="checkbox"><input type="checkbox" name="custom-activities" value="174"><span>Foodie</span></div><div class="checkbox"><input type="checkbox" name="custom-activities" value="32"><span>Gambling</span></div><div class="checkbox"><input type="checkbox" name="custom-activities" value="49"><span>National Parks</span></div><div class="checkbox"><input type="checkbox" name="custom-activities" value="51"><span>Nightlife</span></div><div class="checkbox"><input type="checkbox" name="custom-activities" value="58"><span>Road Trips</span></div><div class="checkbox"><input type="checkbox" name="custom-activities" value="59"><span>Romance</span></div><div class="checkbox"><input type="checkbox" name="custom-activities" value="66"><span>Shopping</span></div><div class="checkbox"><input type="checkbox" name="custom-activities" value="180"><span>Solo</span></div></div>';


/*** Custom Module ***/
    function loadCustomContent() {
        jQuery.ajax({		   
            url: '/custom-content/taxa/ajax/',
            success: function(arrayData) {
               var customData = eval(arrayData);
               var customDestHTML = '<div class="leftcol">';           
               var customInterestHTML = '<div class="leftcol">';
               var customDestData = [];
               var customActivitiesData = [];
               var checkactdups = 0;                 
               for (i=0; i < customData.length; i++) {
                    (customData[i][1] == '') ? friendlyName = customData[i][2] : friendlyName = customData[i][1];
                    if (customData[i][3].indexOf('destinations') >= 0) {                        
                        customDestData.push(friendlyName + "||" + customData[i][0]);
                        
                    } else {
                        if (customActivitiesData.toString().indexOf(friendlyName + "||") >= 0) {checkactdups += 1;}
                        customActivitiesData.push(friendlyName + "||" + customData[i][0]);                        
                    }
                }                
                customDestData.sort();    
                customActivitiesData.sort();
                
                var customDivHalf = Math.round(customDestData.length/2);
                for (i=0; i < customDestData.length; i++) {     
                    if (customDivHalf == 0) {customDestHTML +='</div><div class="leftcol">';}
                    customDestHTML += '<div id="' + customDestData[i].split("||")[1] + '" class="select">' + customDestData[i].split("||")[0] + '</div>';
                    customDivHalf--;
                }
                customDestHTML +='</div>';
                
                            
                var customDivHalf = Math.round((customActivitiesData.length - checkactdups)/2);         
                for (i=0; i < customActivitiesData.length; i++) {                                        
                    if (customDivHalf == 0) {customInterestHTML +='</div><div class="leftcol">';} 
                    if (i < (customActivitiesData.length - 1) && customActivitiesData[i].split("||")[0] == customActivitiesData[i+1].split("||")[0]) {
                        customInterestHTML += '<div class="checkbox"><input type="checkbox" value="' + customActivitiesData[i].split("||")[1] + ';' + customActivitiesData[i+1].split("||")[1] +'" name="custom-activities"><span>' + customActivitiesData[i].split("||")[0] + '</span></div>';
                        i = i + 1;                        
                    } else {
                        customInterestHTML += '<div class="checkbox"><input type="checkbox" value="' + customActivitiesData[i].split("||")[1] +'" name="custom-activities"><span>' + customActivitiesData[i].split("||")[0] + '</span></div>';             
                    }  
                    customDivHalf--;                    
                }                
                 customInterestHTML +='</div>';
                 
                jQuery("#selectDestination .container").replaceWith(customDestHTML);
                jQuery("#checkboxesActivities .container").replaceWith(customInterestHTML);    
                initCustomContent();                
            }
        });
        
    }

    function updateSelectedActivities() {
        var checkedActivities = "SELECT YOUR ACTIVITIES";
        var checkedActivitiesIds = "";
        var $checkboxesActivities = jQuery("#checkboxesActivities input:checked");
        if ($checkboxesActivities.length <= 5) {
            $checkboxesActivities.each(function() {
                if (checkedActivities == "SELECT YOUR ACTIVITIES") {
                    checkedActivities = jQuery(this).parent().text(); 
                    checkedActivitiesIds = jQuery(this).val();               
                } else {
                    checkedActivities = checkedActivities + ",&nbsp;" + jQuery(this).parent().text();
                    checkedActivitiesIds = checkedActivitiesIds + ';' + jQuery(this).val();                
                }
            });
            jQuery("#custom-selectedActivities span").html(checkedActivities); 
            jQuery("#custom-activity-hidden").val(checkedActivitiesIds);
            return true;    
        } else {
            alert("Please select up to 5 activities");
            return false;
        }
    }

    function initCustomContent() {
        jQuery("#custom-content-form").submit(function(){ return false;});

        jQuery("#submit-custom-content").click(function() {
           if (jQuery("#custom-destination-hidden").val() == "") {
                alert("Please select a destination");
                return false;           
           } else {
                if (jQuery("#custom-activity-hidden").val() != "") {
                    var searchTermsURL = jQuery("#custom-destination-hidden").val() + ';' + jQuery("#custom-activity-hidden").val();           
                } else {
                    var searchTermsURL = jQuery("#custom-destination-hidden").val();           
                }
                if (location.pathname.indexOf('qa.') >= 0 || location.pathname.indexOf('dev.') >= 0 || location.href.indexOf('www') >= 0) {
                    var searchURL = '/custom-content/' +  searchTermsURL + '/'; 
                } else {                  
                    var searchURL = 'http://www.budgettravel.com/custom-content/' +  searchTermsURL + '/'; 
                }
                document.location = searchURL;
           }
        })

        jQuery("#selectDestination .select").click(function() {
            jQuery("#custom-selectedDestination span").html(jQuery(this).html());
            jQuery("#custom-destination-hidden").val(jQuery(this).attr("id"));
            jQuery("#custom-selectedDestination").click();
        });


        jQuery("#custom-destination .selectHeader").click(function() {
            if (jQuery(this).attr("id") == 'custom-selectedDestination') {
                jQuery(this).parent().toggleClass("selected");
                jQuery(this).find(".dropDownContent").slideToggle("fast");
            } else {
                jQuery(this).parent().parent().toggleClass("selected");    
                jQuery(this).siblings(".dropDownContent").slideToggle("fast");
            }    
        });
        
         jQuery("#custom-destination").mouseleave(function() { 
            jQuery(this).removeClass("selected"); 
            jQuery(this).find(".dropDownContent").slideUp("fast")
         });

        jQuery("#custom-activities").mouseleave(function() { 
            if ( updateSelectedActivities() == true) {
                jQuery(this).removeClass("selected"); 
                jQuery(this).find(".dropDownContent").slideUp("fast");
            }
        });
            
        jQuery("#custom-activities .selectHeader").click(function() {
            if ( updateSelectedActivities()) {
                if (jQuery(this).attr("id") == 'custom-selectedActivities') {
                    jQuery(this).parent().toggleClass("selected");
                    jQuery(this).find(".dropDownContent").slideToggle("fast");
                } else {
                    jQuery(this).parent().parent().toggleClass("selected");    
                    jQuery(this).siblings(".dropDownContent").slideToggle("fast");
                }
            
            }
        });

        jQuery("#custom-selectedActivities-close").click(function() {
            if ( updateSelectedActivities()) {
                jQuery(this).parent().parent().toggleClass("selected");    
                jQuery(this).siblings(".dropDownContent").slideToggle("fast");        
            }        
        });
    }
/*** END Custom Module ***/   

/** END Choice update variable **/
BTRAV.endChoiceHotels = 1;
 
BTRAV.updateDynPageData = function() {
 jQuery(document).ready(function() {
    jQuery.ajax({
       type: "GET",
       url: "http://www.budgettravel.com/contextdata/",
       dataType: "jsonp",
       jsonpCallback: "updateNavData"
     });
 });     
}

