/*
 * listing.js 
 * Date Created: March 11, 2009
 * Requires: jquery 1.2.3
 * Author: Brandon Quintana
 */
 
var baseURL = '/tivo-tco/';
var imageBaseURL = '/assets/images/findtv/';

jQuery(function($) {
	$.fn.listing = function(settings) {
		var defaults = {
			startTime: initStartDateTime,
			endTime: initEndDateTime,
				offset: channelOffset,
				timezoneOffset: tzOffsetInMin,
				numChannels: channelCount,
				totalChannels: channelListSize,
				loggedIn: isLoggedIn,
				halfHours: 8,
				resizeable: false,
				listingSelector: 'div#listing',
				dateHeaderSelector: 'h2.dateHeader',
				guideSelector: 'div.guide',
				categorySelector: 'input.category',
				jumpToChannelSelector: 'select.jump-to-channel',
				channelsSelector: 'div.channels',
				channelSelector: 'div.channel',
				descriptionSelector: 'div.description',
				dateSelector: 'select.date',
				timeSelector: 'select.time',
				contentSelector: 'div.content',
				dateGoSelector: 'a.datetime-go',
				timeHolderSelector: 'div.timeHolder',
				hourSelector: 'img.hour',
				pageUpSelector: 'img.pageUp',
				pageDownSelector: 'img.pageDown',
				pageLeftSelector: 'img.pageLeft',
				pageRightSelector: 'img.pageRight',
				showSelector: 'a.show-description',
				closeSelector: 'img.close-description',
				lbCloseSelector: 'a.lbClose',
				meta : {
					settings: {
						categories : {
							'tivo:ca.413902' : { //movies
								name: 'movies',
								checked: $('input.category[value="tivo:ca.413902"]').attr('checked'),
								className: 'bg-purple'
							},
							'tivo:ca.413905' : { //sports
								name: 'sports',
								checked: $('input.category[value="tivo:ca.413905"]').attr('checked'),
								className: 'bg-green'
							},
							'tivo:ca.413907' : { //action
								name: 'action',
								checked: $('input.category[value="tivo:ca.413907"]').attr('checked'),
								className: 'bg-orange'
							},
							'tivo:ca.10916167' : { //arts
								name: 'arts',
								checked: $('input.category[value="tivo:ca.10916167"]').attr('checked'),
								className: 'bg-blue'
							},
							'tivo:ca.413897' : { //kids
								name: 'kids',
								checked: $('input.category[value="tivo:ca.413897"]').attr('checked'),
								className: 'bg-grey'
							},
							'tivo:ca.413898' : { //comedy
								name: 'comedy',
								checked: $('input.category[value="tivo:ca.413898"]').attr('checked'),
								className: 'bg-yellow'
							}
						}
					}
				},
				months : ['January', 'February', 'March', 'April', 'May', 
					'June', 'July', 'August', 'September', 'October', 'November', 'December'],
				days : ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
			}; // end defaults
		
		var s = $.extend(defaults, settings);
			
		var c = {
			currentData : '',
			data: []
		};
		
		return this.each(function() {
			/* Initialize
			-------------------------------------------*/
			/**
	 		* @method init
	 		**/
			this.init = function() {	
				this._setHd();
				this._eventManager();
				this._setSize();
			};

			/* Private Methods
			-------------------------------------------*/
			/**
			 * @method _setHd()
			 * Set form controls based on meta data
			 */
			this._setHd = function() {
				var form = $(this).find("div.hd form");				
				// set checkboxes from meta data
				for (var i in s.meta.settings.categories) {
					form.find(s.categorySelector + '[value=' + i + ']').attr("checked",
						s.meta.settings.categories[i].checked ? true : "");
				}
			}
			
			/**
			 * @method _eventManager()
			 **/
			this._eventManager = function() {
				var $this = this;
				
				$(s.listingSelector).bind('click', function(e) {
					var target = $(e.target);
					
					if(target.is(s.categorySelector)) {
						$(s.categorySelector + "[value=" + target.attr('value') + "]").attr("checked", target.attr("checked") ? true : "");
						$this._highlightCategories(target);
					}
					
					if(target.is(s.dateGoSelector)) {
						$this._setStartEndTime($(this).find(s.dateSelector).val() + ' ' + $(this).find(s.timeSelector).val());
						$this._loadData();
						return false;
					}
					
					if(target.is(s.hourSelector)) {
						$this._setStartEndTime(target.parent().attr('rel'));
						$this._loadData();
						return false;
					}
					
					if(target.is(s.pageUpSelector)) {
						s.offset = (s.offset - s.numChannels >= 0) ? s.offset - s.numChannels : 0;
						$this._loadData();
						return false;
					}
					
					if(target.is(s.pageDownSelector)) {
					    s.offset += s.numChannels;
					    
						if ((s.offset + s.numChannels) > s.totalChannels)
							s.offset = s.totalChannels - s.numChannels;
							
						$this._loadData();
						$('html,body').animate({scrollTop: 0}, 1000);
						
						$(s.listingSelector + ' div.loading img').css({
							'top': 40
						});
						
						return false;
					}
					
					if(target.is(s.pageLeftSelector)) {
						var date = $this._formatDate(s.startTime);
						date.setMinutes(date.getMinutes() - (s.halfHours * 30) + 30);
						$this._setStartEndTime(date);
						$this._loadData();
						return false;
					}
					
					if(target.is(s.pageRightSelector)) {
						var date = $this._formatDate(s.endTime);
						date.setMinutes(date.getMinutes() - 30);
						$this._setStartEndTime(date);
						$this._loadData();
						return false;
					}
					
					if(target.is(s.showSelector)) {
						$this._loadDescription(target);
						return false;
					}
					
					if(target.is(s.closeSelector)) {
						$this._closeDescription(target);
						return false;
					}
					
					if(target.is(s.lbCloseSelector)) {
						$this._hideLoading();
					}
				});
				
				$(window).bind('resize', function(e) {
					var target = $(e.target);
					if(s.resizeable) $this._setSize();
				});
				
				$(s.jumpToChannelSelector).bind('change', function(e) {
					s.offset = parseInt($(this).val(),10);
                    if ((s.offset + s.numChannels) > s.totalChannels) {
                        s.offset = s.totalChannels - s.numChannels;
                    }
                    channelOffset = s.offset;
					
					$this._loadData();
				});
				
				$(document).bind('ajaxError', function(e, XMLHttpRequest, ajaxOptions, thrownError){
					var target = $(e.target);					
					//alert('Error requesting content.');					
					$this._hideLoading();
				});
			};

			/**
			 * @method _setStartEndTime()
			 * @params startDate
			 **/
			this._setStartEndTime = function(startDate) {
				// set dropdown, due to date time change in dropdown, hour select, and page left and right
				var st = new Date(startDate);
				this._setSelectDateTime(st);
				
				//Start Time
				st.setMinutes(st.getMinutes() - parseInt(s.timezoneOffset));
				
				s.startTime = this._convertTimeToString(st);
				initStartDateTime = s.startTime;
								
				//End Time
				var et = new Date(st);
				et.setMinutes(et.getMinutes() + (s.halfHours * 30));
					
				s.endTime = this._convertTimeToString(et);
				initEndDateTime = s.endTime;
			};
			
			/**
			 * Set the appropriate values for data/time dropdown
			 */
			this._setSelectDateTime = function(date) {
				var month = (date.getMonth() + 1 < 10 ? '0' : '') + (date.getMonth() + 1);
				var day = (date.getDate() < 10 ? '0' : '') + date.getDate();
				var dateSelect = [month, '/', day, '/', date.getFullYear()].join('');
				$(this).find('select.date[name=date]').val(dateSelect);
				
				var hours = (date.getHours() < 10 ? '0' : '') + date.getHours();
				var hourSelect = [hours, ":00:00"].join('');
				$(this).find('select.time[name=time]').val(hourSelect);
			}
			
			/**
			 * @method _convertTimeToString()
			 * @params date
			 **/
			this._convertTimeToString = function(date) {
				var month = (date.getMonth() + 1 < 10 ? '0' : '') + (date.getMonth() + 1);
				var day = (date.getDate() < 10 ? '0' : '') + date.getDate();
				var fullDate = [date.getFullYear(), '-', month, '-', day];
				
				var hours = (date.getHours() < 10 ? '0' : '') + date.getHours();
				var minutes = (date.getMinutes() < 10 ? '0' : '') + date.getMinutes();
				var seconds = (date.getSeconds() < 10 ? '0' : '') + date.getSeconds()
				var time = [hours, ':', minutes, ':', seconds];

				return fullDate.join('') + '+' + time.join('');
			};

			/**
			 * @method _highlightCategories()
			 * @params trigger
			 **/
			this._highlightCategories = function(trigger) {
				var category = s.meta.settings.categories[trigger.attr('value')];
				category.checked = trigger.attr('checked');
				
				if(category.checked)
					$('.' + category.name).addClass(category.className);
				else
					$('.' + category.name).removeClass(category.className);
			};

			/**
			 * @method _setSize()
			 **/
			this._setSize = function() {
				s.halfHours = Math.ceil($(s.listingSelector).width()/$(s.hourSelector).width());
				this._setStartEndTime(this._formatDate(s.startTime));
				this._loadData();
			};
		
			/**
			 * @method _formatDate()
			 * @param date
			 **/
			this._formatDate = function(dateString) {
				var startYear = dateString.substring(0,4);
				var startMonth = dateString.substring(5,7);
				var startDay = dateString.substring(8,10);
				var startTime = dateString.substring(11,19);
				
				var date = new Date(startMonth + '/' + startDay + '/' + startYear + ' ' + startTime);
				date.setMinutes(date.getMinutes() + parseInt(s.timezoneOffset));
				
				return date;
			}

			/**
			 * @method _setDateHeader()
			 **/
			this._setDateHeader = function() {
				date = this._formatDate(s.startTime);
				return s.days[date.getDay()] + ', ' + s.months[date.getMonth()] + ' ' + date.getDate() + ', ' + date.getFullYear();
			}
			
			/**
			 * @method _hourTemplate()
			 **/
			this._hourTemplate = function() {
				var html = [];
				
				date = this._formatDate(s.startTime);
				
				var hour = date.getHours();
				var halfHour = (hour * 2) + Math.ceil(date.getMinutes()/30);
				
				html.push('<div class="icon">');
				html.push('<img src="' + imageBaseURL + 'gridguide/timebar/sunmoon/tco.gridGuide.sun.' + halfHour + '.gif" width="54" height="37" />');
				html.push('</div>');
				html.push('<div class="hours">');
				html.push('<ul class="clearfix">');
				
				for(var i = 0; i < s.halfHours; i++) {
					var currMonth = (date.getMonth() + 1 < 10 ? '0' : '') + (date.getMonth() + 1);
					var currDay = (date.getDate() < 10 ? '0' : '') + date.getDate();
					var currDate = [currMonth, '/', currDay, '/', date.getFullYear()];
				
					var currHours = (date.getHours() < 10 ? '0' : '') + date.getHours();
					var currMinutes = (date.getMinutes() < 10 ? '0' : '') + date.getMinutes();
					var currSeconds = (date.getSeconds() < 10 ? '0' : '') + date.getSeconds()
					var currTime = [currHours, ':', currMinutes, ':', currSeconds];
					var currDate = currDate.join('') + ' ' + currTime.join('');
				
					html.push('<li>');
					
					html.push('<a rel="' + currDate + '" href="#">');
					html.push('<img class="hour" src="' + imageBaseURL + 'gridguide/timebar/tco.gridGuide.tb.' + halfHour + '.gif" width="159" height="37" /></a>');
					html.push('</li>');
					
					halfHour = (halfHour + 1 > 47) ? 0 : halfHour + 1;
					date.setMinutes(date.getMinutes() + 30);
				}
				
				html.push('</ul>');
				html.push('</div>');
				
				return html.join('');
			}

			/**
			 * @method _channelTemplate()
			 **/
			this._channelTemplate = function(channelData) {
				var html = [];
				
				html.push('<div class="channel">');
				html.push('<div class="left">');
				html.push('<a title="Previous Page" href="#">');
				html.push('<img class="pageLeft" src="' + imageBaseURL + '/gridguide/tco.gridGuide.arrowBack.gif" width="9" height="47" alt="previous"/>');
				html.push('</a>');
				html.push('</div><div class="right">');
				html.push('<a title="Next Page" href="#">');
				html.push('<img class="pageRight" src="' + imageBaseURL + '/gridguide/tco.gridGuide.arrowFwd.gif" width="9" height="47" alt="next"/>');
				html.push('</a>');
				html.push('</div><div class="content">');
				html.push('<div class="name">');
				html.push('<p>' + channelData.channel.channelNumber + '<br/>' + channelData.channel.callSign + '</p>');
				html.push('</div>');
				html.push('<ul class="shows">');
				
				for (var i = 0, length = channelData.offer.length; i < length; i++) {
					var show = channelData.offer[i];
					
					if (i == 0) {
						duration = show.duration - (this._formatDate(s.startTime) - this._formatDate(show.startTime))/1000;
					} else {
						duration = show.duration;
					}
					
					if(duration != 0) {
						var halfHourWidth = $(s.hourSelector).width();
						var width = ((duration/60)*(halfHourWidth/30)) - 1;
					
						html.push('<li');
					
						html.push(' class="' + this._getCategories(show.category) + '"');
					
						html.push(' style="width: ' + width + 'px;">');
						html.push('<div>');
					
						if(typeof show.title != 'undefined' && show.title.length > width/8)
							show.title = show.title.substring(0, Math.floor(width/8)) + '...';
					
						html.push('<h1><a class="show-description" id="');
						html.push(show.offerId.substr(11).replace(/\./g,""));
						html.push('" title="');
						html.push(show.title);
						html.push('" href="');
						html.push(baseURL);
						html.push('go.do?def=data.offer.info.json&offerId=');
						html.push(show.offerId);
						html.push('&collectionId=');
						html.push(show.collectionId);
						html.push('&contentId=');
						html.push(show.contentId);
						html.push('">' + show.title + '</a></h1>');

						var subtitle_desc="";
						if (typeof show.subtitle != 'undefined')
							subtitle_desc = '"' + show.subtitle + '"';
						if(typeof show.description != 'undefined') {
							if (typeof show.subtitle != 'undefined')
								subtitle_desc += ' ';							
							subtitle_desc += show.description;
						}
						if (subtitle_desc.length > width/8)
							subtitle_desc = subtitle_desc.substring(0, Math.floor(width/8)) + '...';

						html.push('<p>' + subtitle_desc + '</p>');
						html.push('</div>');
						html.push('</li>');
					}
				}
				
				html.push('</ul>');
				html.push('</div>');
				html.push('</div>');
				
				return html.join('');
			};
			
			/**
			 * @method _findShowImage()
			 * @param images
			 **/
			this._findShowImage = function(images) {
				var imgsz = "";
				var k = -1;
				for (var i=0; i<images.length; i++) {
					imgsz = images[i].width + "x" + images[i].height;
					if (imgsz == "120x90") { // find best image for show
						return images[i];
					}
					else if (imgsz == "50x75") { // find best image for movie
						return images[i];
					}
					else if (imgsz == "120x100") { // find cast image for show
						k = i; // remember it for now
					}
				}
				return (k != -1 ? images[i] : null); // use cast image if found one, else null
			}
			
			/**
			 * @method _descriptionTemplate()
			 * @param data
			 **/			
			this._descriptionTemplate = function(data) {
				var html = [];
				var marginLeft = 15;
				var offer = data.offer[0];
				
				html.push('<div class="description-content request clearfix">');
				html.push('<a class="close-img" href="#">');
				html.push('<img class="close-description" src="' + imageBaseURL + '/gridguide/tco.gridGuide.prevPane.closeX.gif" />');
				html.push('</a>');
				
				if(typeof offer.credit != 'undefined') {
					if(typeof offer.image != 'undefined') {
						var showImg = this._findShowImage(offer.image);
						if(showImg != null) {
							var showImgUrl = showImg.imageUrl;
							showImgUrl = showImgUrl.substr(showImgUrl.indexOf(".com/") + 4);
							html.push('<div class="description-img">');
							html.push('<img src="' + showImgUrl + '" width="' + showImg.width + '" height="' + showImg.height + '"/>');
							html.push('</div>');
							
							marginLeft = showImg.width + 30;
                        } else {
                            html.push('<div class="description-img">');
                            html.push('<img src="' + imageBaseURL + '/no_show_graphic_bluebg_120w.jpg" width="120" height="70"/>');
                            html.push('</div>');
                            
                            marginLeft = 150;
						}
                    } else {
                        html.push('<div class="description-img">');
                        html.push('<img src="' + imageBaseURL + '/no_show_graphic_bluebg_120w.jpg" width="120" height="70"/>');
                        html.push('</div>');
                        
                        marginLeft = 150;
					} 
				} else {
                    html.push('<div class="description-img">');
                    html.push('<img src="' + imageBaseURL + '/no_show_graphic_bluebg_120w.jpg" width="120" height="70"/>');
                    html.push('</div>');
                    
                    marginLeft = 150;
				}
				
				html.push('<ul class="description-recording">');
				var recordParam = [];
				if (s.loggedIn) {
				    recordParam.push('offerId=');
				    recordParam.push(offer.offerId);
				} else {
					recordParam.push('collectionId=');
                    recordParam.push(offer.collectionId);
                    recordParam.push('&contentId=');
                    recordParam.push(offer.contentId);
                    recordParam.push('&channelId=');
                    recordParam.push(offer.channel.channelNumber);
                    recordParam.push('|');
                    recordParam.push(offer.channel.stationId);
                    recordParam.push('|');
                    recordParam.push(offer.channel.sourceType);
                    recordParam.push('&mStartTime=');
                    recordParam.push(offer.startTime);                
                }
                recordParam = recordParam.join('');
                
                html.push('<li><div class="button_recordThisEpisode"><a class="bb_recordButton" href="/tivo-tco/1clickepisode.do?' + recordParam + '">1-Click Record</a></div></li>');
                if (offer.episodic) {
					html.push('<li><div class="button_getASeasonPass"><a class="bb_seasonpassButton" href="/tivo-tco/1clickseason.do?' + recordParam + '">1-Click Season Pass</a></div></li>');
				}
                html.push('<li><div class="recordWithOptions"><a class="bb_recordingoptionsButton" href="/tivo-tco/recoptions.do?' + recordParam + '">Record with options</a></div></li>');
                
				var showURL = [baseURL];
				showURL.push('program/show.do?');
				showURL.push('&offerId=');
				showURL.push(offer.offerId);
				
				showURL = showURL.join('');
				
				html.push('<li><a href="' + showURL + '">More about this show</a></li>');
				html.push('</ul>');
				html.push('<div class="description-data" style="margin-left: ' + marginLeft + 'px">');
				html.push('<h1>' + offer.title + '</h1>');
				
				html.push('<p>');
                if(typeof offer.subtitle != 'undefined')
					html.push('&quot;' + offer.subtitle + '&quot;');
                if(typeof offer.description != 'undefined') {
					if (typeof offer.subtitle != 'undefined')
						html.push('&#160;');
					html.push(offer.description);
				}
                html.push('</p>');
				
				var date = this._formatDate(offer.startTime);
				
				html.push('<p class="date">');
				html.push(s.days[date.getDay()]);
				html.push(', ');
				html.push(s.months[date.getMonth()]);
				html.push(' ');
				html.push(date.getDate());
				html.push('</p>');
				html.push('<p class="time">');
				
				if (date.getHours() >= 12 ) {
					var ampm = 'PM';
					var hours = date.getHours() - 12;
				} else {
					var ampm = 'AM';
					var hours = date.getHours();
				}
				
				if (hours == 0)
				    hours = 12;
				
				var minutes = (date.getMinutes() < 10) ? '0' + date.getMinutes() : date.getMinutes();
				
				html.push(hours + ':' + minutes + ' ' + ampm);
				
				date.setSeconds(date.getSeconds() + offer.duration);
				
				if (date.getHours() >= 12 ) {
					var ampm = 'PM';
					var hours = date.getHours() - 12;
				} else {
					var ampm = 'AM';
					var hours = date.getHours();
				}
				
                if (hours == 0)
                    hours = 12;

				var minutes = (date.getMinutes() < 10) ? '0' + date.getMinutes() : date.getMinutes();
				
				html.push(' - ');
				html.push(hours + ':' + minutes + ' ' + ampm);
				
				html.push(', ' + offer.channel.channelNumber + '&nbsp;' + offer.channel.callSign + '</p>');
				html.push('</div>');
				html.push('</div>');
			
				return html.join('');
			
			};
			
			/**
			 * @method _loadData()
			 **/
			this._loadData = function() {
				var $this = this;
				var url = [baseURL];
				url.push('ggJson.do?offset=');
				url.push(s.offset);
				url.push('&count=');
				url.push(s.numChannels);
				url.push('&tsn=&maxEndTime=');
				url.push(escape(s.startTime));
				url.push('&minStartTime=');
				url.push(escape(s.endTime));
				url.push('&_=');
				
				url = url.join('');
				
				$(s.listingSelector + ' ' + s.dateHeaderSelector).html(this._setDateHeader());
				
				if (typeof c.data[url] != 'undefined') {
					if(typeof c.data[url].gridRow != 'undefined')
						this._parseData(c.data[url]);
				} else {
					this._showLoading();
					$.getJSON(url, function(data) {
						$this._hideLoading();
						c.data[url] = data;
						if(typeof data.gridRow != 'undefined')
							$this._parseData(data);
						else
							alert('Channel information does not exist for requested date and time.');

					    $this._loadFirstShow();
					});
				}
			};
			
			/**
			 * @method _loadDescription()
			 * @param trigger
			 **/
			this._loadDescription = function(trigger) {
				var $this = this;

				var url = trigger.attr('href');
				if (typeof c.data[url] != 'undefined') {
					this._showDescription(c.data[url], trigger);
				} else {
					$.getJSON(url, function(data) {
						c.data[url] = data;
						$this._showDescription(data, trigger);
					});
				}
			};
			
			this._loadFirstShow = function() {
				if (displayOfferId != "") {
					var firstshow = $('div.channels div.channel a#' + displayOfferId.substr(11).replace(/\./g,""));
					if (firstshow.length > 0) {
						this._loadDescription(firstshow);
					}
					displayOfferId = "";
				}
			};
			
			/**
			 * @method _parseData()
			 * @param data
			 **/
			this._parseData = function(data) {
				
				var html = [];

				for (var i = 0, length = data.gridRow.length; i < length; i++) {
					row = data.gridRow[i];
					html.push(this._channelTemplate(row));
				}

				$(s.listingSelector + ' ' + s.channelsSelector).html(html.join(''));
				//$(s.listingSelector + ' ' + s.dateHeaderSelector).html(this._setDateHeader()); // call this line sooner in loadData
				$(s.listingSelector + ' ' + s.timeHolderSelector).html(this._hourTemplate());
			};
			
			/**
			 * @method _getCategories()
			 **/
			this._getCategories = function(categories) {
				var classNames = [];
				
				if(typeof categories != 'undefined') {
					for(var i = 0, length = categories.length; i < length; i++) {
						if (typeof s.meta.settings.categories[categories[i].categoryId] != 'undefined') {
							classNames.push(s.meta.settings.categories[categories[i].categoryId].name);
						
							if(s.meta.settings.categories[categories[i].categoryId].checked)
								classNames.push(s.meta.settings.categories[categories[i].categoryId].className);
						}
					}
				}
				
				return classNames.join(' ');
			};
			
			/**
			 * @method _showDescription()
			 * @param data
			 **/
			this._showDescription = function(data, trigger) {
				var channel = trigger.parents(s.channelSelector);
				var data = this._descriptionTemplate(data);

				if(channel.next().is(s.descriptionSelector)) {
					if(c.currentData == data) {
						channel.next().slideUp();
						c.currentData = '';
					}
					else  {
						channel.next().html(data);

						if (c.currentData == '')
							channel.next().slideDown();	
							
						c.currentData = data;				
					}
				} else {
					$(s.descriptionSelector).slideUp(function(){$(this).remove();});
					channel.after('<div class="description"></div>');
					channel.next().html(data).slideDown();
					c.currentData = data;				
				}
				
				$("a.bb_recordButton").setOneClickEpisode();
				$("a.bb_seasonpassButton").setOneClickSeason();
				$("a.bb_recordingoptionsButton").setRecordingOptions();
			};
			
			/**
			 * @method _closeDescription()
			 * @param trigger
			 **/
			this._closeDescription = function(trigger) {
				trigger.parents(s.descriptionSelector).slideUp(function(){$(this).remove();});
			};
			
			/**
			 * @method _showLoading()
			 * @param target
			 **/
			this._showLoading = function() {
				var target = $(s.listingSelector + ' div.bd');

				target.append('<div class="loading"><img src="/assets/images/findtv/icons/loading_animation.gif" /></div>');
				
				$(s.listingSelector + ' div.loading').css({
					'position': 'absolute',
					'height': target.height() + 'px',
					'width': target.width() + 'px',
					'top': target.position().top + parseInt(target.css('padding-top')),
					'left': target.position().left,
					'padding': '0',
					opacity: 0.75,
					'z-index': '1'
				});
				
				var loadingTop = ($(s.listingSelector + ' div.loading').height() < $(window).scrollTop() + 40) ? 25 : $(window).scrollTop() + 40;
				
				$(s.listingSelector + ' div.loading img').css({
					'top': loadingTop
				});
			};
			
			/**
			 * @method _hideLoading()
			 **/
			this._hideLoading = function() {
				$(s.listingSelector + ' div.loading').remove();
			};
			
			/* Public Methods
			-------------------------------------------*/
		
			//Call initialize
			this.init();

		});
	};	
});

jQuery(document).ready(function($) {
	$('div#listing').listing({listingSelector:'div#listing'});
});

function loadPopUpGrid() {
	jQuery('div#popup-listing').listing({listingSelector:'div#popup-listing', numChannels: 50, resizeable: true});
	jQuery('div#popup-listing div.section').add_corners('section').end();
  	jQuery('div#popup-listing .buttonSmall, div#popup-listing .buttonLarge').make_buttons().end();
}
