/*-------------------------------------------*\
                 DYNAMIC LEADS
\*-------------------------------------------*/
var currentTab=1;		//Keeps track of the current tab for rotating.
var dlRotate;			//Stores the interval for tab switching so it can be stopped.
var dlRunning = false;	//Keeps track of whether or not the auto scroll is running.
var dlNumTabs;			//Counts the number of tabs once the DOM is ready.
var firstLoad = true;	//Modifies the Toggle function on the first page load.
var dlFade = false;	//Keeps track of fading well it is occuring.

function dlToggle() { //Starts/stops the auto switching
	if(dlRunning) {
		$("a#dlToggle").css("background-position","-26px 0");
		clearInterval(dlRotate);
		dlRunning = false;
	} else {
		$("a#dlToggle").css("background-position","-13px 0");
		firstLoad?firstLoad=false:dlCycle("next");
		dlRotate = setInterval('dlCycle("'+'next'+'")', 7000);
		dlRunning = true;
	}
}

function dlCycle(direction) { //Goes to next or previous tab
	if(direction == "next") {
		dlSwitch(currentTab>=dlNumTabs?1:currentTab+1);
	} else {
		dlSwitch(currentTab==1?dlNumTabs:currentTab-1);
	}
}

function dlSwitch(tabNum) { //Goes to the requested tab
	if(!dlFade) {
		dlFade = true;
		$("#dlTabs .activeTab").removeClass("activeTab");
		$("#dlTabs li").eq(tabNum-1).addClass("activeTab");
		$(".dlTab").eq(currentTab-1).fadeOut(200,function(){
			$(".dlTab").eq(tabNum-1).fadeIn(200,function(){dlFade = false;});
		});
		currentTab=parseInt(tabNum);
	}
}

var isCTRL = false;
var isFocus = false;
function arrowSwitch(Event) {
	if(Event==null) Event=event; //IE doesn't pass the event!
	if(Event.keyCode == 37 && isCTRL) { //left 37
		if(dlRunning) dlToggle();
		dlCycle("previous");
	} else if(Event.keyCode == 39 && isCTRL) { //right 39
		if(dlRunning) dlToggle();
		dlCycle("next");
	} else if(Event.keyCode == 17) {
		isCTRL = true;
	}
	
	if(Event.keyCode == 9 && !isFocus) { //outlines are turned off for firefox until the user hits tab
		$("a").addClass("withFocus");
		isFocus = true;
	}
	
}

function arrowCancel(Event) {
	if(Event==null) Event=event; //IE doesn't pass the event!
	if(Event.keyCode == 17) {
		isCTRL = false;
	}	
}

/*-------------------------------------------*\
                 TAB SWITCH
\*-------------------------------------------*/
var tabFade = false;	//Keeps track of fading well it is occuring.
function tabSwitch(container,newTab) { //Goes to the requested tab
	if(!tabFade && !$("#"+container+" .activeTab").is("#"+newTab+"Tab")) {
		tabFade = true;
		var oldTab = $("#"+newTab+"List").siblings();
		$("#"+container+" .activeTab").removeClass("activeTab");
		$("#"+newTab+"Tab").addClass("activeTab");
		oldTab.fadeOut(200,function(){
			$("#"+newTab+"List").fadeIn(200,function(){tabFade = false;});
		});
	}
}

/*-------------------------------------------*\
                 MAGAZINE SWITCH
\*-------------------------------------------*/
var magFade = false;	//Keeps track of fading well it is occuring.
var currentMag = 0;
var magNum;				//Keeps track of the number of magazines.
function magSwitch(direction) { //Goes to the requested tab
	if(!magFade) {
		magFade = true;
		if(direction=="next") {
			if((currentMag + 1) < magNum)
				nextMag = currentMag + 1;
			else
				nextMag = 0;
		} else {
			if((currentMag - 1) >= 0)
				nextMag = currentMag - 1;
			else
				nextMag = magNum-1;
		}
		$(".magazine").eq(currentMag).fadeOut(200,function(){
			$(".magazine").eq(nextMag).fadeIn(200,function(){magFade = false;});
		});
		currentMag = nextMag;
	}
}

/*-------------------------------------------*\
                 WEATHER
\*-------------------------------------------*/
function bindChooseCity() {
	$("#chooseCity").bind("click", function(){ //Choose city for weather
		window.open("/Homepage/includes/popups/weather.html",null,"height=260,width=420,status=no,toolbar=no,menubar=no,location=no");
		return false;
	});
}

/*-------------------------------------------*\
                 COOKIES
\*-------------------------------------------*/
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(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;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

/*-------------------------------------------*\
                 DROP DOWN
\*-------------------------------------------*/
function dropDown(dropdown) {
	$("#"+dropdown).toggle();
	
	//stupid hack, works around one of IE's z-index bugs.
	if($.browser.msie && dropdown=="ddNewspapers")
		$("#magazines h1").toggleClass("ieDDFix");
	
	if($("#"+dropdown).css("display") == "none") {
		$("html").unbind();
	} else {
		$("html").bind("click", function(){
		  dropDown(dropdown);
		});	
	}
}

/*-------------------------------------------*\
                 PARTNERS
\*-------------------------------------------*/
Array.prototype.has = function(value) {
	var i;
	for (var i = 0, loopCnt = this.length; i < loopCnt; i++) {
		if (this[i] == value) return true;
	}
	return false;
};

function randomPartners() {
	var howMany = $("#partners .partner").size()-1;
	var choosen = new Array();
	var theCount = 0;
	choosen[0] = "-1";
	$("#partners .partner").removeClass("show").removeClass("last");
	while(choosen.length != 3){
		rand = Math.round(howMany*Math.random());
		if(!choosen.has(rand)) {
			choosen[theCount] = rand;
			theCount++;
		}
	}
	$("#partners .partner").eq(choosen[0]).addClass("show");
	$("#partners .partner").eq(choosen[1]).addClass("show");
	$("#partners .partner").eq(choosen[2]).addClass("show");
}

/*-------------------------------------------*\
                 VIDEO
\*-------------------------------------------*/
function _canoevideo(anchor)
{
  var selectedAnchor = jQuery(anchor);
  
  // clear tabs
  jQuery("#videoPlayer .tabs ul li").each(function ()
  {
    jQuery(this).removeClass('current');
  });

  selectedAnchor.parent().addClass('current');

  // get playlist
  var playlist = selectedAnchor.attr('rel').substring(9);

 jQuery.getJSON('http://en.video.canoe.tv/api/playlist/'+playlist+'?format=json&limit=' + videoPlaylistSize + '&callback=?',
    function(data){
      $('#videoPlayer .content').empty();
      $.each(data.videos, function(i,video)
      {
        if ( i == 0 )
        {
          $('#videoPlayer .content').append('<a href="'+video.link+'" title="'+video.name+'" target="_blank"><img class="featured" src="'+video.videostill_url+'" alt="pic for '+video.name+'" width="188" height="141" /></a>');
        }

        $('#videoPlayer .content').append('<div class="video"><a href="'+video.link+'" title="'+video.name+'" target="_blank"><img src="'+video.thumbnail_url+'" width="40" height="30" /></a><p><a href="'+video.link+'" title="'+video.name+'" target="_blank">'+video.name+'</a></p></div>');
    });
  });

  return false;
}



/*-------------------------------------------*\
                 SHOPPING
\*-------------------------------------------*/
var shopFade = false;	//Keeps track of fading well it is occuring.
var currentShop = 0;
var currentAuction = -1;
var isAuction = false;


function cycleShop(num) {
	var text = '<h2><a href="'+shoppingData[num]['link']+'">'+shoppingData[num]['title']+'</a></h2>';
	text = text + '<p class="redText"><a href="'+shoppingData[num]['link']+'">'+shoppingData[num]['price']+'</a></p>';
	text = text + '<p class="paddingBottom"><a href="'+shoppingData[num]['link']+'" class="boxLink">Compare Prices</a></p>'
	text = text + '<p>'+shoppingData[num]['store']+'</p>';
	$("#shopImage").html('<a href="'+shoppingData[num]['link']+'"><img src="'+shoppingData[num]['image']+'" alt="Product Image" /></a>');
	$("#shoppingText").html(text);
}

function cycleAuction(num) {
	var objRegExp = /<IMG BORDER=0 SRC="(.*)" ALT=\"Product Picture\" style=\"border:1px solid #fff;\">/;
	var text = '<h2><a href="'+auction_data[num]['link']+'">'+auction_data[num]['title']+'</a></h2>';
	text = text + '<p class="redText"><a href="'+auction_data[num]['link']+'">Curent Bid: $'+auction_data[num]['current_bid']+'</a></p>';
	//text = text + '<p class="paddingBottom">Bids: '+auction_data[num]['bids']+'</p>';
	text = text + '<p class="paddingBottom"><a href="'+auction_data[num]['link']+'" class="boxLink">Bid</a></p>'
	text = text + '<p>Ends: '+auction_data[num]['ends']+'</p>';
	$("#shoppingText").html(text);
	$("#shopImage").html('<a href="'+auction_data[num]['link']+'"><img src="'+auction_data[num]['image'].replace(objRegExp, "$1")+'" alt="Product Image" id="auctionImage" /></a>');
}
/* Random sorting value... */
function randOrd(){
   return (Math.round(Math.random())-0.5);
}

function shopSwitch(direction) {
	if(direction == "next") {
		if(isAuction) {
			currentAuction++;
			if(currentAuction==8) currentAuction = 0;
		} else {
			currentShop++;
			if(currentShop==8) currentShop = 0;
		}
	} else {
		if(isAuction) {
			currentAuction--;
			if(currentAuction==-1) currentAuction = 7;
		} else {
			currentShop--;
			if(currentShop==-1) currentShop = 7;
		}
	}
	if(isAuction) {
		cycleAuction(currentAuction);
	} else {
		cycleShop(currentShop);
	}
	
	//uncomment the below line to add auctions to the widget and set var isAuction = false; to true
	//isAuction = !isAuction;
}


/*-------------------------------------------*\
            RANDOMIZE CLASSES
\*-------------------------------------------*/
function randomClass(classname){
	var contents=randomClass.collectElementbyClass(classname)
	contents.text.sort(function() {return 0.5 - Math.random();})
	for (var i=0; i<contents.ref.length; i++){
		contents.ref[i].innerHTML=contents.text[i]
		//contents.ref[i].style.display="block"
	}
}

randomClass.collectElementbyClass=function(classname){ //return two arrays containing elements with specified classname, plus their innerHTML content
	var classnameRE=new RegExp("(^|\\s+)"+classname+"($|\\s+)", "i") //regular expression to screen for classname within element
	var contentobj=new Object()
	contentobj.ref=new Array() //array containing references to the participating contents
	contentobj.text=new Array() //array containing participating contents' contents (innerHTML property)
	var alltags=document.all? document.all : document.getElementsByTagName("*")
	for (var i=0; i<alltags.length; i++){
		if (typeof alltags[i].className=="string" && alltags[i].className.search(classnameRE)!=-1){
			contentobj.ref[contentobj.ref.length]=alltags[i]
			contentobj.text[contentobj.text.length]=alltags[i].innerHTML
		}
	}
	return contentobj
}
/*-------------------------------------------*\
                 LAVALIFE
\*-------------------------------------------*/
function setInterruptPage(n) {
   styleChange(ss_picture).innerHTML = interruptPage;
   styleChange(ss_name).innerHTML = '<img src="http://www.lavalife.com/images/xxxx-pixel.gif" width="1" height="14" border=0>';
   styleChange('ss_text').innerHTML = '<img src="http://www.lavalife.com/images/xxxx-pixel.gif" width="1" height="15" border=0>';
}

function go(dir, gender) {
   ss_picture = 'ss_picture_both';
   ss_name    = 'ss_name_both';

   if (intrpCount == 0 || intrpCountM == 0 || intrpCountF == 0) {
      if (dir != 0) {
         if (gender == 1) {
            intrpCountF = intervalInterruptPage;
         }
         else if (gender == 2) {
            intrpCountM = intervalInterruptPage ;
         }
         else {
            intrpCount = intervalInterruptPage ;
         }

         setInterruptPage(1);
      }
   } else {
      if (dir != 0) {
         if (gender == 1) {
            intrpCountF--;
         }
         else if (gender == 2) {
            intrpCountM--
         }
         else {
            intrpCount--
         }
      }

      if (gender == 1) {
         count  = countF + dir;
         if (count > maxPicF) count = 1;
         if (count < 1) count = maxPicF;

         countF = count;
         currGender = 1;
      } else if (gender == 2) {
         count  = countM + dir;
         if (count > maxPicM) count = 1;
         if (count < 1) count = maxPicM;

         countM = count;
         currGender = 2;
      } else {
         if ((currGender == 2 && dir == 1) || (currGender == 1 && dir == -1)) {
            count  = countBoth + dir;
         }

         if (count > maxPicBoth && currGender == 2) {
            count = 1;
         }

         if (count < 1 && currGender == 1) {
            count = maxPicBoth;
         }

         countBoth = count;
         if (currGender == 1) {
            currGender = 2 ;
         } else {
            currGender = 1 ;
         }
      }

	  styleChange(ss_picture).innerHTML = getSSPicture(gender);
      styleChange(ss_name).innerHTML = getSSId(gender);
      styleChange('ss_text').innerHTML = getSSText();
   }
}

function getViewLink(gender) {
   var seeking = '?i_am=F&seeking=M';

   if (gender == 1) {
      seeking = '?i_am=M&seeking=F';
   }

   var memberLink = 'http://www.lavalife.com/clickthru/clickthru.act?' +  seeking + '&idname=' + escape(slideShowIds[currGender][count]) + '&id=externalSlideshow&context=ad77';

   return memberLink;
}

function getSSPicture(gender) {
   var memberLink = getViewLink(gender);
   var tmp = '<a href="' + memberLink + '" target="_new"><img src="' + photo_directory + slideShowPics[currGender][count] + suffix +  '" border="0" class="vertAlign"></a>';
   return tmp;
}

function getSSId(gender) {
   var memberLink = getViewLink(gender);
   return '<a href="' + memberLink + '">'+ slideShowIds[currGender][count] + '</a>';
}

function getSSText() {
   return '<img src="http://www.lavalife.com/images/msntab/messenger_actualMember.gif" alt="" width="148" height="15" border="0" style="margin-left: 2px;">';
}


