/**
 * The slot grid component.
 * Uses a SlotgridSource implementation (model) to create a grid layout
 * in it's DOM-parent container with as many slot items as possibly fit.
 * Dynamic resizing, pagination & ad space are also implemented here.
 * @author HUGE inc.
 * @version 1.0 
 */
var _bReload = false;
function SlotGrid(source) {

	// a SlotgridSource instance
	this.source = source;
	
	var instance = this;
	this.content = $('<div class="slotgridcontent"/>');
	this.currentOffset = 0;
	this.slotCount = 12;
	this.slots = new Array();
	
	this.createControls();
	
	//observe window resize event
	var instance = this;
	$(window).bind('resize', function() {
		if(typeof(instance.resizeTimeout) != 'undefined') {
			window.clearTimeout(instance.resizeTimeout);
		}
		instance.resizeTimeout = window.setTimeout(function() { instance.resizeContent();}, 20);
	});
};

/**
 * Static slotgrid properties
 * @author HUGE inc.
 * @version 1.0
 */
SlotGrid.slotHeight = 145;
SlotGrid.slotWidth = 145;

/**
 * creates the slotgrid's dom skeleton
 * @author HUGE inc.
 * @version 1.0 
 */
SlotGrid.prototype.createControls = function() {
	var instance = this;
	
	// holds pagination & displayoptions
	this.pActions = $('<div/>')
		.addClass('slotgridactions');
	
	// Pagination	
	this.pPagination = $('<div/>')
		.addClass('pagination')
		.prependTo(this.pActions);
	this.btnPrev = $('<a/>')
		.addClass('btnPrev')
		.attr('title', 'Previous Page')
		.attr('href', '')
		.html('Prev')
		.click(function() { instance.prev(); return false; })
		.prependTo(this.pPagination);
	$('<span/>').html('Page:').prependTo(this.pPagination);
	this.tbPage = $('<input type="text"/>')
		.addClass('tbPage')
		.attr('size', 1)
		.change(function() { instance.goTo(instance.tbPage[0].value - 1); })
		.prependTo(this.pPagination);
		
	/* fix for Jira AS-29, IE does not trigger 'change' event for text fields on enter */
	if($.browser.msie) {
		this.tbPage.keypress(function(e) {
			if(e.keyCode == 13) {
				instance.goTo(instance.tbPage[0].value - 1);
			}
		});
	}
	
	this.lPagination = $('<span/>')
		.prependTo(this.pPagination);
	this.btnNext = $('<a/>')
		.addClass('btnNext')
		.attr('title', 'Next Page')
		.attr('href', '')
		.html('Next')
		.click(function() { instance.next();  return false; })
		.prependTo(this.pPagination);		
	
	// Display options
	this.pSorting = $('<div/>')
		.addClass('sorting')
		.appendTo(this.pActions);
	$('<span/>').html('Sort:').appendTo(this.pSorting);
	
	var displayOptions = this.source.getDisplayOptions();
	for(var i = 0; i < displayOptions.length; i++) {
		var btn = $('<a href="">' + displayOptions[i] + '</a>');
		btn.addClass('btnDisplayOption');
		btn.click(function() {
			instance.pSorting.find('.btnDisplayOption').removeClass('active');
			$(this).addClass('active');
			instance.source.setDisplayOption($(this).html());
			
			// reset pagination for new display option
			instance.currentOffset = 0;
			instance.asyncLoadData();
			
			return false;
		});
		
		if(this.source.getDisplayOption() == displayOptions[i]) {
			btn.addClass('active');
		}
		
		btn.appendTo(this.pSorting);
	}
	
	// hide display option pane if there is only one
	if(displayOptions.length < 2) {
		this.pSorting.hide();
	}
};

/**
 * append slotgrid to a specific dom node 
 * @author HUGE inc.
 * @version 1.0 
 */
SlotGrid.prototype.appendTo = function(node) {
	var instance = this;
	node.append(this.pActions);
	node.append(this.content);
	
	// apply png fix (only works /after/ elements are added to DOM)
	fixpng(this.btnNext);
	fixpng(this.btnPrev);
	
	// trigger resize event, the slotgrid has been added to the dom and now knows it's dimensions
	this.resizeContent();
};

/**
 * Resizes slotgrid, repopulates lots if necessary & adjusts pagination
 * bound to the window resize event
 * @author HUGE inc.
 * @version 1.0 
 */ 
SlotGrid.prototype.resizeContent = function() {
	// evaluate dimensions
	var theHeight = Math.max($(window).innerHeight() - 180, SlotGrid.slotHeight * 2);
	var theWidth = Math.max($(window).innerWidth() - 80, SlotGrid.slotWidth * 4);
	
	// calculate maximum slot item count
	this.numWide = Math.floor(theWidth / SlotGrid.slotWidth);
	this.numHigh = Math.floor(theHeight / SlotGrid.slotHeight);

	// subtract 5 item spaces for the ads
	this.slotCount = this.numWide * this.numHigh - 5;

	theHeight = this.numHigh * SlotGrid.slotHeight;
	theWidth = this.numWide * SlotGrid.slotWidth + 10;
	
	// adjust the width and height to make them snug
	this.content.height(theHeight).width(theWidth);
	
	// center grid horizontally
	var padding = this.content.parent().innerWidth() / 2 - theWidth / 2;
	this.content.siblings('.slotgridactions').width(theWidth);
	
	// align section title with grid (this is not ideal, a css solution would be better)
	this.content.siblings('.indextitle').width(theWidth);

	// create slots & ads
	
	this.writeAds();
	
	this.loadState();
	this.asyncLoadData();
};
SlotGrid.prototype.writeAds = function() {
	this.content.empty();
	for(var i = 0; i < this.slotCount; i++) {
		// insert the ads where required
		if (i == this.numWide - 3) {
			var bb = $('<div class="bigad">' +
				'<div class="adheader">ad</div>' +
				'<div class="billboard"/>' +
			'</div>').appendTo(this.content);
			AdFactory.loadBillboard(function(html) {
				bb.find('.billboard').html(html);
			});
		}
		
		// move 125x125 ad one over and one down from the big ad in the grid
		if (i == Math.min(this.numWide * 2 - 6, this.slotCount)) {
			var sb = $('<div class="sponsorbadge"><span class="adtag">ad</span></div>').appendTo(this.content);
			AdFactory.loadSponsorshipBadge(function(html) { sb.append(html); });
		}
		
		this.slots[i] = $('<div class="slot"/>').appendTo(this.content);
	}
}
/**
 * load items for current page from SlotgridSource and populate slots, asynchronously
 * @author HUGE inc.
 * @version 1.0 
 */
SlotGrid.prototype.asyncLoadData = function() {
	
	if(!this.source.initialized) {
		this.source.init(this, 'asyncLoadDataCallback');
	} else {
		this.asyncLoadDataCallback();
	}
};

/**
 * internal callback handler for asyncLoadData
 * @author HUGE inc.
 * @version 1.0 
 */
SlotGrid.prototype.asyncLoadDataCallback = function() {
	
	var instance = this;
	
	//adjust currentOffset so that it still shows no matter what page it is on after the resize
	this.currentOffset = this.currentOffset > 0 && this.currentOffset < this.source.getTotalItems() ? this.currentOffset : 0;
	this.currentOffset = (this.slotCount - 2) * this.getPageForIndex(this.currentOffset);
	this.currentOffset += this.currentOffset > 0 ? 1 : 0; // first page has no prev button 
	
	// determine how many items we need to retrieve
	var buffersize = Math.min(this.source.getTotalItems() - this.currentOffset, this.slotCount);
	buffersize -= buffersize == this.slotCount && this.currentOffset > 0 ? 1 : 0; //reserve first slot for previous button
	buffersize -= this.currentOffset + buffersize < this.source.getTotalItems() ? 1 : 0; //reserve last slot for next button
	
	for(var i = 0; i < this.slots.length; i++) {
		this.slots[i].empty();
	}
	
	this.source.loadItems(this.currentOffset, buffersize, function(items) {
		instance.populateSlots(items);
		instance.updatePaginationInfo();
	});
	
	// track every request of a single grid page
	Tracker.track(Show.configuration.showName + ' - ' + Indexpage.currentSection, 'Shows');
};

/**
 * jump to a certain page, mind that page numbers are dependend on window dimensions
 * @author HUGE inc.
 * @version 1.0 
 */
SlotGrid.prototype.goTo = function(page) {

	//if requested page is invalid, reset pagination info and abort 
	if(isNaN(page)
		|| page == this.getPageForIndex(this.currentOffset)	//current page
		|| page < 0
		|| page > this.getPageForIndex(this.source.getTotalItems() - 1)) {
		
		this.updatePaginationInfo();
		return;
	}
	
	//navigate to requested page
	this.currentOffset = page == 0 ? 0 : (this.slotCount - 2) * page + 1;
	this.writeAds();
	this.asyncLoadData();
};

/**
 * move to next page, asynchronously
 * @author HUGE inc.
 * @version 1.0 
 */
SlotGrid.prototype.next = function() {
	
	this.writeAds();	
	
	this.currentOffset += this.slotCount - 1 - (this.currentOffset > 0 ? 1 : 0);
	this.asyncLoadData();
};

/**
 * move to previous page, asynchronously
 * @author HUGE inc.
 * @version 1.0 
 */
SlotGrid.prototype.prev = function() {
	
	this.writeAds();	
	
	this.currentOffset -= this.slotCount - 1; // -1 because previous page certainly has a next button
	this.currentOffset += this.currentOffset > 0 ? 1 : 0; // maybe it also has a previous button
	this.asyncLoadData();
};

/**
 * update paginationinfo panel showing current and total number of pages and small prev/next buttons 
 * @author HUGE inc.
 * @version 1.0 
 */
SlotGrid.prototype.updatePaginationInfo = function() {
	
	var curPage = this.getPageForIndex(this.currentOffset) + 1;
	var totalPages = (this.getPageForIndex(this.source.getTotalItems() - 1) + 1);
	
	this.tbPage[0].value = curPage;
	this.lPagination.html(' of ' + totalPages);
	
	// hide pagination panel if there is only one page
	if(totalPages < 2) {
		this.pPagination.hide();
	} else {
		this.pPagination.show();
	}
};

/**
 * returns the page index for a given item index (dependend on window dimensions)
 * @author HUGE inc.
 * @version 1.0 
 */
SlotGrid.prototype.getPageForIndex = function(idx) {
	idx = Math.max(idx - 1, 0); // shift left because first page has no prev button
	var res = Math.floor(idx / (this.slotCount - 2));
	
	//special case: items fit exactly into slotgrid, then we save one next button   
	if(idx == this.source.getTotalItems() - 2 && idx % (this.slotCount - 2) == 0) {
		res = Math.max(res - 1, 0);
	}
	
	return res;
};

/**
 * populates slots with any given item array.
 * @author HUGE inc.
 * @version 1.0 
 */
SlotGrid.prototype.populateSlots = function(items) {
	
	var instance = this;
	
	// set indexes for prev/next buttons
	var btnNextIndex = this.slotCount - 1;
	var btnPrevIndex = 0;
		
	for(var i = 0, j = 0; i < this.slotCount; i++) {
		this.slots[i].empty();
		
		// insert previous button where applicable
		if(i == btnPrevIndex) {
			if(this.currentOffset > 0) {
				this.slots[i].empty().append($('<a class="prev" href="">Prev</a>')
					.click(function() { instance.prev(); return false;})).show();
				this.btnPrev.show();
				continue;
			} else {
				this.btnPrev.hide();
			}
		}
		
		// insert next button where applicable
		if(i == btnNextIndex) {
			if(this.currentOffset + items.length < this.source.getTotalItems()) {
				this.slots[i].empty().append($('<a class="next" href="">Next</a>')
					.click(function() { instance.next(); return false; })).show();
				this.btnNext.show();
				continue;
			} else {
				this.btnNext.hide();
			}
		}
		
		// fill slot with item or hide
		if(j < items.length) {
			this.slots[i].attr('class', 'slot'); //reset css
			this.slots[i].append(items[j++].html()).show();
		} else {
			this.slots[i].hide();
		} 
	}
	
	// apply pngfix to overlay and cornercuts
	$('.slot .overlay, .slot .cornercut').ifixpng();
	this.saveState();
};

/**
 * persists the slotgrid's state (i.e. current offset)
 * @author HUGE inc.
 * @version 1.0 
 */
SlotGrid.prototype.saveState = function() {
	var uniqueId = this.content.parents('.onePane:first')[0].id + '_sg_state';
	document.cookie = uniqueId + '=' + this.currentOffset;
};

/**
 * loads slotgrid's state (i.e. current offset)
 * @author HUGE inc.
 * @version 1.0 
 */
SlotGrid.prototype.loadState = function() {
	try {
		var uniqueId = this.content.parents('.onePane:first')[0].id + '_sg_state';
		var match = new RegExp(/=(\d+);/).exec(document.cookie.substring(document.cookie.indexOf(uniqueId)));
		if(match != null) {
			this.currentOffset = match[1];
		}
	} catch(err) {
		//irrelevant
	}
};

/**
 * function to calculate the slotgrid width given a certain window size
 * @author HUGE inc.
 * @version 1.0
 */
SlotGrid.calcWidth = function() {
	var w = Math.max($(window).innerWidth() - 80, SlotGrid.slotWidth * 4);
	var numWide = Math.floor(w / SlotGrid.slotWidth);
	return numWide * SlotGrid.slotWidth + 10;
};
function DownloadItem(){
    extend(this, SlotItem);
    this.css = "download";
    this.links = new Array();
    this.baseUrl = "http://i.cdn.turner.com/adultswim/shows/downloads/shows/"
}

DownloadItem.prototype.addLink = function(C, A, B){
    this.links[this.links.length] = {
        text: C,
        url: A,
        target: B
    }
};
DownloadItem.prototype.contentHtml = function(){
    var C = "";
    for (var B = 0; B < this.links.length; B++) {
        var A = this.links[B].target ? this.links[B].target : "_self";
        C += '<a href="' + this.links[B].url + '" target="' + A + '">' + this.links[B].text + "</a>&nbsp;&nbsp;"
    }
    return C
};
function GenericItem(A, D, C, B){
    extend(this, SlotItem);
    this.thumb = A;
    this.title = D;
    this.subtitle = C;
    this.setUrl(B);
    this.css = "generic"
}

GenericItem.prototype.contentHtml = function(){
    return '<span class="subtitle">' + this.subtitle + "</span>"
};
function IconItem(B){
    extend(this, DownloadItem);
    var A = this.baseUrl + Show.configuration.ids.downloadsId;
    this.type = "icon";
    this.thumb = A + "/icon/" + B + ".jpg";
    this.title = "Icons";
    this.setUrl(A + "/icon/" + B + ".zip");
    this.addLink("Download", this.url)
}

var Mp3Item_uniqueId = 0;
function Mp3Item(D, C){
    extend(this, DownloadItem);
    var B = this.baseUrl + Show.configuration.ids.downloadsId;
    this.type = "mp3";
    this.thumb = B + "/mp3/" + D + ".jpg";
    this.mp3 = B + "/mp3/" + C;
    this.addLink("Download", this.mp3, "_blank");
    this.id = "mp3_" + (++Mp3Item_uniqueId);
    var A = this;
    this.click = function(){
        $(this).html('<div id="' + A.id + '">sorry, you need at least flash player 9</div>');
        A.buildPlayer();
        Tracker.track(Show.configuration.showName + " - " + A.title, "Shows")
    }
}

Mp3Item.prototype.buildPlayer = function(){
    var A = new SWFObject(root_path + "global/swf/mp3player.swf", "player", "119", "90", "9", "#FFF");
    A.addVariable("strId", this.id);
    A.addVariable("strSoundURL", this.mp3);
    A.addVariable("strImageURL", this.thumb);
    A.addVariable("strPlayURL", root_path + "global/imgs/play.png");
    A.addVariable("strPauseURL", root_path + "global/imgs/pause.png");
    A.addParam("allowScriptAccess", "always");
    A.write(this.id)
};
function Mp3ItemPause(A){
    $("#" + A).parents(".slot").removeClass("slot-on")
}

function Mp3ItemPlay(A){
    $("#" + A).parents(".slot").addClass("slot-on")
}

function ScreensaverItem(B){
    extend(this, DownloadItem);
    var A = this.baseUrl + Show.configuration.ids.downloadsId;
    this.type = "screensaver";
    this.thumb = A + "/ss/" + B + ".jpg";
    this.title = "Screensaver";
    this.addLink("PC", A + "/ss/pc/" + B + ".zip");
    this.addLink("Mac", A + "/ss/mac/" + B + ".zip")
}

function SlotItem(){
    this.type = "";
    this.thumb = "";
    this.title = "";
    this.click = null
}

SlotItem.prototype.html = function(){
    var B = $('<div class="' + this.css + " " + this.type + '"><span class="title">' + this.title + "</span>" + this.contentHtml() + "</div>");
    var A = $('<div class="img" title="' + this.title + '"><img width="119" src="' + this.thumb + '"/><div class="cornercut"/></div>');
    if (this.click != null) {
        A.append('<div class="overlay hide"/>');
        A.hover(function(){
            $(".overlay", this).show()
        }, function(){
            $(".overlay", this).hide()
        });
        A.css("cursor", "pointer");
        A.click(this.click)
    }
    B.prepend(A);
    return B
};
SlotItem.prototype.setUrl = function(A){
    this.url = A;
    this.click = function(){
        window.location = A
    }
};
SlotItem.prototype.contentHtml = function(){
    return ""
};
function VideoItem(){
    extend(this, SlotItem)
}

VideoItem.prototype.contentHtml = function(){
    var A = '<span class="rankingAndViews">Rating: ' + this.ranking + "<br/>Views: " + this.numberOfViews + '</span><span class="ratingAndDate">' + this.rating + "<br/>" + this.launchDate + "</span>";
    return A
};
VideoItem.prototype.setUrl = function(B){
    var A = this;
    this.click = function(C){
        //Tracker.track(Show.configuration.showName + " - " + A.title, "Shows");
        window.location = B
    }
};
function WallpaperItem(B){
    extend(this, DownloadItem);
    var A = this.baseUrl + Show.configuration.ids.downloadsId;
    this.type = "wallpaper";
    this.thumb = A + "/wp/thumbs/" + B + ".jpg";
    this.title = "Wallpaper";
    this.addLink("Large", A + "/wp/" + B + "_1600.jpg", "_blank");
    this.addLink("Medium", A + "/wp/" + B + "_1024.jpg", "_blank");
    this.addLink("Small", A + "/wp/" + B + "_800.jpg", "_blank")
}

function DownloadsFeed(){
    extend(this, SlotgridSource);
    this.sort = "";
    this.data = null
}

DownloadsFeed.prototype.init = function(callbackObject, callbackFunction){
    var instance = this;
    if (this.initialized) {
        callbackObject[callbackFunction]()
    }
    else {
        $.ajax({
            type: "GET",
            url: "/shows/downloads/dlJSON.js",
            dataType: "json",
            async: true,
            complete: function(data){
                instance.initialized = true;
                var response = eval("(" + (data.responseText.substring(data.responseText.indexOf("{"))) + ")");
                instance.data = response.content[Show.configuration.ids.downloadsId];
                instance.initTypesArray();
                callbackObject[callbackFunction]()
            }
        })
    }
};
DownloadsFeed.prototype.getTotalItems = function(){
    var B = 0;
    for (var A in this.types) {
        B += this.displayOption == "All" || this.displayOption == this.types[A].name ? this.types[A].len : 0
    }
    return B
};
DownloadsFeed.prototype.initTypesArray = function(){
    var A = this;
    this.types = [{
        name: "Wallpapers",
        len: this.data.wallpapers,
        factoryMethod: function(B){
            return new WallpaperItem(B)
        }
    }, {
        name: "Mp3s",
        len: this.data.mp3s.length,
        factoryMethod: function(B){
            var D = A.data.mp3s[B - 1];
            var C = new Mp3Item(B, D.filePath);
            C.title = "MP3 - &#8216;" + D.title + "&#8217;";
            return C
        }
    }, {
        name: "Icons",
        len: this.data.icons,
        factoryMethod: function(B){
            return new IconItem(B)
        }
    }, {
        name: "Screensavers",
        len: this.data.ss,
        factoryMethod: function(B){
            return new ScreensaverItem(B)
        }
    }]
};
DownloadsFeed.prototype.loadItems = function(F, E, H){
    var C = new Array();
    var G = 0;
    var A = F;
    for (var D in this.types) {
        if (this.displayOption == "All" || this.displayOption == this.types[D].name) {
            for (var B = A - G; B < this.types[D].len && C.length < E; B++, A++) {
                C[C.length] = this.types[D].factoryMethod(B + 1)
            }
            G += this.types[D].len
        }
    }
    H(C)
};
DownloadsFeed.prototype.getDisplayOptions = function(){
    var B = ["All"];
    for (var A = 0; A < this.types; A++) {
        if (this.types.len > 0) {
            B[B.length] = this.types.name
        }
    }
    return B
};
function GenericFeed(A){
    extend(this, SlotgridSource);
    this.feedname = A;
    this.show = "birdman";
    this.sort = "";
    this.data = null
}

GenericFeed.prototype.init = function(C, B){
    var A = this;
    if (this.initialized) {
        C[B]()
    }
    else {
        $.ajax({
            type: "GET",
            url: "feeds/generic/" + this.feedname + ".js",
            dataType: "json",
            async: true,
            success: function(D){
                A.data = D.items;
                A.initialized = true;
                C[B]()
            }
        })
    }
};
GenericFeed.prototype.getTotalItems = function(){
    return this.data.length
};
GenericFeed.prototype.loadItems = function(E, D, G){
    var C = new Array();
    var F = 0;
    var A = E;
    for (var B = E; B < this.data.length && C.length <= D; B++) {
        C[C.length] = new GenericItem(this.data[B].thumb, this.data[B].title, this.data[B].subtitle, this.data[B].url)
    }
    G(C)
};
function SlotgridSource(){
    this.displayOption = "All";
    this.initialized = false
}

SlotgridSource.prototype.getDisplayOptions = function(){
    return ["All"]
};
SlotgridSource.prototype.setDisplayOption = function(A){
    this.displayOption = A
};
SlotgridSource.prototype.getDisplayOption = function(){
    return this.displayOption
};
function SmallshowFeed(){
    extend(this, SlotgridSource);
    this.sort = "";
    this.data = null
}

SmallshowFeed.prototype.init = function(C, B){
    var A = this;
    if (this.initialized) {
        C[B]()
    }
    else {
        $.ajax({
            type: "GET",
            url: "feeds/smallshow.js",
            dataType: "json",
            async: true,
            success: function(D){
                A.initialized = true;
                A.data = D;
                C[B]()
            }
        })
    }
};
SmallshowFeed.prototype.getTotalItems = function(){
    return this.data.length
};
SmallshowFeed.prototype.loadItems = function(E, D, F){
    var B = new Array();
    for (var A = E; A < D; A++) {
        var C = null;
        switch (this.data[A].type) {
            case "video":
                C = new VideoItem();
                C.css = "cli";
                C.setUrl(this.data[A].url);
                C.thumb = this.data[A].thumb;
                C.title = this.data[A].title;
                C.ranking = this.data[A].ranking;
                C.numberOfViews = this.data[A].views;
                C.rating = this.data[A].rating;
                C.launchDate = this.data[A].date;
                break;
            case "generic":
                C = new GenericItem();
                C.title = this.data[A].title;
                C.subtitle = this.data[A].subtitle;
                C.thumb = this.data[A].thumb;
                C.setUrl(this.data[A].url);
                C.css = new RegExp(/williamsstreet\.com/).exec(this.data[A].thumb) != null ? "product" : "generic";
                break;
            case "mp3":
                C = new Mp3Item(this.data[A].index, this.data[A].file);
                C.title = "MP3 - &#8216;" + this.data[A].title + "&#8217;";
                break;
            case "wallpaper":
                C = new WallpaperItem(this.data[A].index);
                break;
            case "icons":
                C = new IconItem(this.data[A].index);
                break;
            case "screensaver":
                C = new ScreensaverItem(this.data[A].index);
                break
        }
        if (C != null) {
            B[B.length] = C
        }
    }
    F(B)
};
function StoreFeed(A){
    extend(this, SlotgridSource);
    this.sort = "";
    this.data = null
}

StoreFeed.prototype.init = function(C, B){
    var A = this;
    if (this.initialized) {
        C[B]()
    }
    else {
        $.ajax({
            type: "GET",
            url: "/shows/global/feeds/store.xml",
            dataType: "xml",
            async: true,
            complete: function(D){
                A.data = $('product[show="' + Show.configuration.ids.storeId + '"]', D.responseXML);
                this.initialized = true;
                C[B]()
            }
        })
    }
};
StoreFeed.prototype.getTotalItems = function(){
    return this.data.length
};
StoreFeed.prototype.loadItems = function(F, E, H){
    var C = new Array();
    var G = 0;
    var A = F;
    for (var B = F; B < this.data.length && C.length <= E; B++) {
        var D = new GenericItem($("thumbnail", this.data[B]).text(), "Price $ " + $("price", this.data[B]).text(), $("name", this.data[B]).text(), $("url", this.data[B]).text());
        D.css += " product" + ($("in_stock", this.data[B]).text() == "true" ? "" : " outofstock");
        C[C.length] = D
    }
    H(C)
};
function VideosFeed(){
    extend(this, SlotgridSource);
    this.url = PROXY_PREFIX + "/asfix-svc/episodeSearch/getAllEpisodes";
    this.totalItems = -1;
    this.displayOption = "Newest"
}

VideosFeed.prototype.init = function(C, B){
    var A = this;
    if (this.initialized) {
        C[B]()
    }
    else {
        $.ajax({
            type: "GET",
            url: this.url,
            dataType: "xml",
            data: this.getFeedParameters(1, 0),
            async: true,
            success: function(D){
                A.totalItems = $("episodes", D).attr("totalItems");
                A.initialized = true;
                C[B]()
            }
        })
    }
};
VideosFeed.prototype.getFeedParameters = function(A, C){
    var B = {
        limit: A,
        offset: C,
        categoryName: Show.configuration.show_type,
        filterByEpisodeType: "",
        filterByCollectionId: Show.configuration.ids.vmaId,
		networkName: 'AS',
        r: "1202760270203"
    };
    switch (this.displayOption) {
        case "Newest":
            B.sortByDate = "DESC";
            break;
        case "Popular":
            B.sortByVideoRequest = "DESC";
            break
    }
    return B
};
VideosFeed.prototype.getTotalItems = function(){
    return this.totalItems
};
VideosFeed.prototype.loadItems = function(C, B, D){
    var A = this;
    $.ajax({
        type: "GET",
        url: this.url,
        dataType: "xml",
        data: this.getFeedParameters(B, C),
        complete: function(H){
            var K = $("episode", H.responseXML);
            var G = new Array();
            for (var F = 0, E = K.length; F < E; F++) {
                var I = $(K[F]);
                var J = new VideoItem();
                J.title = I.attr("title");
				J.collectionTitle = I.attr("collectionTitle")
                J.setUrl("http://video.adultswim.com/" + formatLink(J.collectionTitle) + "/" + formatLink(J.title) + ".html");
                J.css = I.attr("episodeType").toLowerCase();
                J.ranking = I.attr("ranking");
                J.numberOfViews = I.attr("numberOfViews");
                J.rating = I.attr("rating");
                J.launchDate = I.attr("launchDate");
                J.thumb = I.attr("thumbnailUrl");
                G[G.length] = J
            }
            D(G)
        }
    })
};
VideosFeed.prototype.getDisplayOptions = function(){
    return ["Newest", "Popular"]
};

 
var regexChars = new RegExp(/[~`!@#\$\%\^\&*\(\)_\+=\{\}\[\]\|\\;:\'\"<>,\.\?\/]/g)
 
function formatLink(str) {
	return $.trim(str.toLowerCase().replace(regexChars, '')).replace(/ /g, '-').replace(/-{2,}/g,'-').replace(/-$/g,'');
}