var $ = jQuery;
// Method to reload ads
function reloadAd(adSize, h_ord, w, h){
	h_tile+=1;
	frameId='frame-'+adSize;
	
	if(!document.getElementById(frameId)){
			
			var adFrame = $("<iframe />")
			var adSrc   = '/php/ads/ad-tags.php?h_ord='+h_ord+'&size='+adSize+'&section='+section+'&post='+post+'&h_tile='+h_tile;
 			adFrame.attr("src",adSrc);
			adFrame.attr("scrolling","no");
			adFrame.attr("width",w);
			adFrame.attr("height",h);
			adFrame.attr("frameborder",0)
			var adDiv = $("#"+adSize);
			adDiv.empty();
			adDiv.append(adFrame);
	
	}else{
   	
		document.getElementById(frameId).src = '/php/ads/ad-tags.php?h_ord='+h_ord+'&size='+adSize+'&section='+section+'&post='+post+'&h_tile='+h_tile;
	
	}
return true;
}
function get_page_url(url){
	var page = url+'#'+currentPage;
	return page;
}
// Track refresh in Google Analytics
function track_pageview(args){
	var ref = (typeof args.ref == 'undefined') ? "" : args.ref;
	var url = (typeof args.url == 'undefined') ? "" : args.url;
	var pageTracker = _gat._getTracker("UA-932072-1");
	pageTracker._trackPageview(url + ref); 
}
//search box
$(function() {
	$('.s-text').focus(function() {
		$(this).val('');
	});
});

//
// Adapted from:
// http://www.dynamicdrive.com/dynamicindex17/ajaxtabscontent/
//
//	AJAX
//
function ajaxtabs(args){
	this.containerDivId 	= args.containerDivId;
	this.contentDivId	 	= args.contentDivId;
	this.pageurl			= args.pageurl;
	this.objName			= args.objName;

	this.connect			= function(parentObj){
		$("#"+this.containerDivId).css("background" , "#eee url(/images/xxlmag2010/marquee-tabs-loading.gif) no-repeat center"); // Show loading gif

    	this.page_request = false;

    	if (window.ActiveXObject){ //Test support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
    		try {
    		this.page_request = new ActiveXObject("Msxml2.XMLHTTP")
    		} 
    		catch (e){
    			try{
    			this.page_request = new ActiveXObject("Microsoft.XMLHTTP")
    			}
    			catch (e){}
    		}
    	}
    	else if (window.XMLHttpRequest) // if Mozilla, Safari etc
    		this.page_request = new XMLHttpRequest()
    	else
    		return false


    	var ajaxfriendlyurl=this.pageurl.replace(/^http:\/\/[^\/]+\//i, "http://"+window.location.hostname+"/");
	
    	this.page_request.onreadystatechange=function(){ parentObj.loadpage() };

    	this.page_request.open('GET', ajaxfriendlyurl, true)
    	this.page_request.send(null)
	};
	this.loadpage			= function(){
	  	if (this.page_request.readyState == 4 ){
	  	    $("#"+this.contentDivId).append(this.page_request.responseText);

	  	    $("#"+this.containerDivId).css("background" , "#eee");// Hide loading gif
	  	}

    }
}

//
// CHARTBEAT
//
function topwidget(apikey, divid, theme, limit, show)
{
  this.apikey = apikey;
  this.divid = divid;
  this.theme = theme;
  this.limit = limit;
  this.show = show;

  if (!this.theme)
    this.theme = "";

  if (!this.limit)
    this.limit = 5;

  var thisobj = this;

  var jsonp = 'topwidget.cback' + Math.round(Math.random()*10000000);
  eval(jsonp + "= function(data) { thisobj.draw(data); }");

  this.host = location.host;

  var dataurl = 'http://api.chartbeat.com/toppages/?host='+this.clean_domain(this.host)+'&jsonp=' + jsonp + '&apikey=' + apikey + "&limit=" + this.limit;

  var headID = document.getElementById("popular");         
  var newScript = document.createElement('script');
  newScript.type = 'text/javascript';
  newScript.src = dataurl;
  headID.appendChild(newScript);

}
topwidget.sort = function(a, b)
{
  if (a["count"] > b["count"])
    return -1;
  if (a["count"] < b["count"])
    return 1;

  return 0;
}
topwidget.prototype.draw = function(data)
{

    // Scan data for urls we don't want to show and remove them from the array
    for (var s = 0; s < data.length && s < this.limit; ++s){
        href = this.clean_domain(this.host) + data[s]["path"];
        if(href in {'xxlmag.com/':'','xxlmag.com/online/?cat=17':'','xxlmag.com/online/?cat=17&paged=2':''}){
            data.splice(s,1)
        }
    }

  var html = '<ul class="post-list">';

  if (!data.length)
    html += '<li>currently no pages listed</li>';

  for (var x = 0; x < data.length && x < this.show; ++x)
  {
    href = this.clean_domain(this.host) + data[x]["path"]  
    
    var title = data[x]["i"];
    if (!title)
      title = data[x]["path"];
      
    html += '<li><a href="http://www.' + href + '"  target="_top">' + this.truncate(title, 55) + '</a></li>';
  
  }

  html += '</ul>';

  if (this.divid)
    document.getElementById(this.divid).innerHTML += html;
  else
    document.write(html);
}
topwidget.prototype.truncate = function(str, len)
{
  str = str.replace("XXLmag.com - » ", "")
  
	if (str.length <= len)
    return str;

  return str.substr(str, len - 3) + "...";
}
topwidget.prototype.clean_domain = function(domain)
{
  domain = domain.replace(/^https?:\/\//i,'');
  domain = domain.replace(/\s*/g,'');
  domain = domain.replace(/^(www.)/i,'');
  domain = domain.replace(/\/.*/g,'');
  domain = domain.replace(/[^0-9A-Za-z.-]*/g,'');

  return domain;
}

//
// sG gallery methods
//
var curImg = get_anchor();
function prev_img(totalImages){

    if( curImg > 1 ){
        prevImg = curImg - 1;
    }
    else{ 
        prevImg = totalImages;
    }

    refresh(imgData[prevImg][0], imgData[prevImg][1], imgData[prevImg][2], prevImg, totalImages , imgData[prevImg][3]);
}
function next_img(totalImgs){

    curImg = parseInt(curImg);

    if(curImg == totalImgs){
        var nextImg = 1;
    }
    else{
        var nextImg = curImg + 1;
    }

    refresh(imgData[nextImg][0], imgData[nextImg][1], imgData[nextImg][2], nextImg, totalImgs, imgData[nextImg][3]);
		
}
function refresh(imgUrl, imgTitle, imgDescription, index, numImages, largeURL){

   // Change Image, Title, Description
   $('#sg-gallery_image').attr("src", imgUrl);
	$('#sg-enlarge').attr("href", largeURL);
	$('#sg-gallery_image').attr("alt", imgTitle);
	$('#sg-gallery_image').attr("title", imgTitle);
   $('#sg-image-title').html(imgTitle);
   $('#sg-image-description').html(imgDescription);

	// refresh ads
   CampaignManager.look();
   reloadAd('leaderboard', h_ord, 728, 90);
  	reloadAd('skyscraper', h_ord, 160, 600);
   reloadAd('medrec', h_ord, 300, 250);
    
   // Change URL
   set_anchor(index);
   prevImg = curImg;
   curImg = index;

   // Image 1 of totalImage
   $('#sg-curImage').html(curImg + ' ');
    
}
function get_page_url(url){
	var page = url+'#'+curImg;
	return page;
}
function get_anchor(){
    var re = /#[0-9]+$/; 
    var match = re.exec(document.location.toString());
    hash = 1;
    if (match != null) var hash = match[0].substr(1);
    return hash;
}
//Add anchor tag to URL
function set_anchor(anchor){
	//remove existing anchors
    var url = document.location.toString();
    var re = /#[0-9]+$/;
    url = url.replace(re, '');
    document.location = url + '#' + anchor;
}
$(function(){
		if(typeof imgData != "undefined"){
			var uri = '\''+ document.location.pathname +'\'';
	
			var totalImgs = $(imgData).size();
		  		totalImgs -=1;
        
			var prevClick = 'prev_img(' + totalImgs + ');track_pageview({url:get_page_url('+ uri + ')});return false;';
			var nextClick = 'next_img(' + totalImgs + ');track_pageview({url:get_page_url('+ uri + ')});return false';

			var topControls = '';
			topControls +='<a href="#" class="back" onclick="'+ prevClick +'">Previous</a>';
		   topControls +='<span id="sg-image-count"><span id="sg-curImage">' + curImg + ' </span>of ' + totalImgs + '</span>';
		   topControls +='<a href="#" class="next" onclick="'+ nextClick +'">Next</a>';
		   $('#sg-top-controls').html(topControls);

			var photoOverlayNav = '';
			photoOverlayNav +='<a onclick="'+ prevClick +'"><div id="sg-prev-button"></div></a>';
		   photoOverlayNav +='<a onclick="'+ nextClick +'"><div id="sg-next-button"></div></a>';
			$('#sg-image-container').prepend(photoOverlayNav);

		    // Display Main Image
		    anchor = get_anchor();
		    if(anchor){
		        thisImg = imgData[anchor];
		    }else{
		        thisImg = imgData[1];
		    }

			//Display Photo, Caption, and Description
			$('#sg-main-image').html('<img id="sg-gallery_image" src="' + thisImg[0] + '"' + ' title="'+thisImg[1]+'"'+' alt="' + thisImg[1] + '">');
		   $('#sg-image-title').html(imgData[anchor][1]);
		  	$('#sg-image-description').html(imgData[anchor][2]);
	
			if(typeof thumbData != "undefined"){
				for(var x in thumbData ){
					$('#sg-thumbnails').append('<a style="cursor:pointer;" onClick="refresh(imgData['+x+'][0], imgData['+x+'][1], imgData['+x+'][2], '+x+', '+ totalImgs +', imgData['+x+'][3]);"><img id="thumb-'+ x +'" src="' + thumbData[x] + '"></a>');
				}
			}
		}
}); // Closes jQuery Function

//
// MARQUEE SCRIPT updated 2010.2.16
//
function xxlMarquee(args){
      	if(!args){
      		this.postNum		= 4;
      		this.changeSpeed 	= 6000;
      		this.imgHeight 	= 350;
				this.headlineWidth= 200;
				this.slideSpeed 	= this.changeSpeed / 16;
      	}else{
				this.postNum 		= (typeof args.postNum == 'undefined') ? 			4 			: args.postNum-1;
      		this.changeSpeed 	= (typeof args.changeSpeed == 'undefined') ? 	6000 		: args.changeSpeed;
      		this.imgHeight 	= (typeof args.imgHeight == 'undefined') ? 		350 		: args.imgHeight;
				this.headlineWidth= (typeof args.headlineWidth == 'undefined') ? 	200 		: args.headlineWidth;
				this.slideSpeed 	= (typeof args.slideSpeed == 'undefined') ? 		this.changeSpeed / 16 		: args.slideSpeed;
      	}

      	// define for local use
			postNum		= this.postNum;
      	changeSpeed = this.changeSpeed;
      	mgHeight = this.imgHeight;
			headlineWidth = this.headlineWidth
      	slideSpeed  = this.slideSpeed;
			distance = $("#image-container").height();
}
xxlMarquee.prototype.autoSlide = function(){	

		if( $("#image-container a:last").is(":visible") )
			nextLi = $("#image-container a:first");
		else 
			nextLi = $("#image-container a:visible").next("a"); 
			
		nextLi.show().css("top",distance*-1); // Show next li and move to top
		$("#marquee-nav .active").removeClass("active");
		var next = nextLi.attr("rel")
		$("#marquee-nav a[rel="+next+"]").addClass("active");
		
		$("#image-container a:visible").each(function(index){   // move visible slides down 
			var curPos = $(this).css("top");

			var nextPos = parseInt(curPos)+distance;
			$(this).animate({"top":nextPos},slideSpeed,function(){ 
				if( parseInt( $(this).css("top") ) == distance ){
					$(this).hide();
					$(this).css("top",distance*-1);
				}
			});
		})
		
		xxlMarquee.prototype.changeHeadline(next);
}
xxlMarquee.prototype.ManualSlide = function(next){
		$("#headline li").each(function(){ $(this).stop(true , true); })
		$("#image-container a").each(function(){ $(this).stop(true , true); })
		
		$("#image-container a.active").removeClass("active");
		$("#image-container a[rel="+next+"]").addClass("active");

		nextLi = $("#image-container a[rel="+next+"]"); 
		nextLi.show().css("top",distance*-1);

		// Stop all previous animations

		$("#image-container a:visible").each(function(){ // move visible slides down 

			var curPos = $(this).css("top");
			var nextPos = parseInt(curPos)+distance;

			$(this).animate({"top":nextPos},slideSpeed,function(){
				if( parseInt( $(this).css("top") ) == distance ){
					$(this).hide();
					$(this).css("top",distance*-1);
				}
			});
		})

		xxlMarquee.prototype.changeHeadline(next);

}
xxlMarquee.prototype.changeHeadline = function(next){
  
	if (next == jsMarqueeData.length){
		var next = 0
	}

	var hlPos = headlineWidth*(-1);
	
	$("#headline li.active").animate({"left" : -213},slideSpeed/3,function(){
			$(this).hide().removeClass("active");
			$("#headline li[rel="+next+"]").animate({"left": "0px"},slideSpeed/3,function(){}).addClass("active").show();
	});
}
xxlMarquee.prototype.startInt = function (){slideInterval = window.setInterval("xxlMarquee.prototype.autoSlide();", changeSpeed);}
xxlMarquee.prototype.stopInt  = function (){window.clearInterval(slideInterval);}
xxlMarquee.prototype.init = function (){
	xxlMarquee.prototype.startInt();
	$(".force-display").removeClass("force-display");
	$("#image-container a:first").show();
	$("#headline li:first").show().css("left","0px").addClass("active");
	$("#highlight-container").mouseover(function(){xxlMarquee.prototype.stopInt();})
	$("#highlight-container").mouseout(function(){xxlMarquee.prototype.startInt();});
	$("#marquee-nav a:first").addClass("active")


	// HOME FUNCTIONS
	$("#marquee-nav a").mouseover(
	
		function(){
			xxlMarquee.prototype.stopInt();
		
			if($(this).hasClass("active")){
				}else{
					xxlMarquee.prototype.ManualSlide($(this).attr("rel"))
					$("#marquee-nav a.active").removeClass("active");
					$(this).addClass("active");
				}
		})
}
	
AudioPlayer.setup("http://www.xxlmag.com/wp-content/plugins/audio-player/assets/player.swf?ver=2.0.4.1", {width:"290",animation:"no",encode:"yes",initialvolume:"60",remaining:"no",noinfo:"no",buffer:"5",checkpolicy:"no",rtl:"no",bg:"000000",text:"cc0000",leftbg:"AAAAAA",lefticon:"323232",volslider:"323232",voltrack:"eeeeee",rightbg:"9c9c9c",rightbghover:"999999",righticon:"333333",righticonhover:"ffffff",track:"E8E8E8",loader:"D12128",border:"666666",tracker:"CCCCCC",skip:"000000",pagebg:"FFFFFF",transparentpagebg:"no"});
