var seletedid= null;
var redirected = 0;

function initTabs(_hold, tabs_hold, nav_hold, _autorotate, _switchTime){
	$j(_hold).each(function(){
		var _timer;
		var _btn = $j(this).find(nav_hold+' a');
		var _tabs = $j(this).find(tabs_hold).children();
		var _tabCount = _btn.length-1;
		_tabs.hide();
		var _a = _btn.index(_btn.filter('.selected:eq(0)')); 
		if(_a == -1) _a = 0;
		_btn.removeClass('selected').eq(_a).addClass('selected');
		if(_btn.get(_a)){
		_tabs.hide().filter(_btn.get(_a).hash).show();
		}
		_btn.click(function(){ 
			if($j(this).hasClass('more')) {
				var _currentIndex = _btn.index(_btn.filter('.selected:eq(0)'));
				if(_currentIndex<_tabCount-1) _btn.eq(++_currentIndex).trigger('click');
				
			} else {
				_tabs.hide().filter(this.hash).show();
				_btn.removeClass('selected'); 
				$j(this).addClass('selected');
				
			}
			return false;
		});
		

		function nextSlide() {
			if(_autorotate && _switchTime) {
				_timer = setTimeout(function(){
					var _currentIndex = _btn.index(_btn.filter('.selected:eq(0)'));
					if(_currentIndex<_tabCount) _currentIndex++;
					else _currentIndex=0;
					_btn.eq(_currentIndex).trigger('click');
					nextSlide();
				},_switchTime);
			}
		}
		if(_autorotate && _switchTime) {
			_timer = setTimeout(function(){
				nextSlide();
			},_switchTime);
		}
	});
}
//initTabs_rotator('div.tabs.video-banner','div.banner','ul.tabNavigation',true,5000);

function initTabs_rotator(_hold, tabs_hold, nav_hold, _autorotate, _switchTime){
	$j(_hold).each(function(){
		var _timer;
		var _btn = $j(this).find(nav_hold+' a');
		var _tabs = $j(this).find(tabs_hold).children();
		var _tabCount = _btn.length-1;
		_tabs.hide();
		var _a = _btn.index(_btn.filter('.selected:eq(0)')); 
		if(_a == -1) _a = 0;
		_btn.removeClass('selected').eq(_a).addClass('selected');
		_tabs.hide().filter(_btn.get(_a).id).show();
		
		_btn.focus(function(){ 
							
			if($j(this).hasClass('more')) {
				var _currentIndex = _btn.index(_btn.filter('.selected:eq(0)'));
				if(_currentIndex<_tabCount-1) _btn.eq(++_currentIndex).trigger('focus');
				
			} else {
				_tabs.hide().filter(this.id).show();
				_btn.removeClass('selected'); 
				$j(this).addClass('selected');
				
			}
			return false;
		});
		_btn.hover(function(){ 
							
			if($j(this).hasClass('more')) {
				var _currentIndex = _btn.index(_btn.filter('.selected:eq(0)'));
				if(_currentIndex<_tabCount-1) _btn.eq(++_currentIndex).trigger('click');
				_autorotate = false;
				
			} else {
				_tabs.hide().filter(this.id).show();
				_btn.removeClass('selected'); 
				$j(this).addClass('selected');
				_autorotate = false;
				clearTimeout(_timer);
				clearTimeout(_timer);
				clearTimeout(_timer);
				
				
			}
			return false;
		});
		

		function nextSlide() {
			if(_autorotate && _switchTime) {
				clearTimeout(_timer2);
				_timer = setTimeout(function(){
					var _currentIndex = _btn.index(_btn.filter('.selected:eq(0)'));
					if(_currentIndex<_tabCount) _currentIndex++;
					else _currentIndex=0;
					_btn.eq(_currentIndex).trigger('focus');
					nextSlide();
				},_switchTime);
			}
		}
		if(_autorotate && _switchTime) {
			_timer2 = setTimeout(function(){
				nextSlide();
			},_switchTime);
		}
	});
}


function initExpandOnToday(){
	var _holder = $j('div.on-today');
	_holder.each(function(){
		var _list = $j('ul', $j(this)).find('li:gt(4)').hide();
		var _btn = $j(this).find('span.btn-expand');
		_btn.click(function()
		{
			if($j(this).hasClass("shown"))
			{
				$j(this).removeClass("shown");
				_list.each(function(){$j(this).hide(200);})
			} else
			{
				$j(this).addClass('shown');
				_list.each(function(){$j(this).show(200);})
			}
			return false;
		});
	})
}

function initAlphbet(){
	var _hold = $j("div.alphaholder");
	_hold.each(function(){
		var _nav = $j("ul.alphanavigation");
		var _numLink = $j("li a", _nav);
		var _itemHold = $j("ul.alphalist");
		var _item = $j("> li", _itemHold);
		var _lable = $j(this).find("span.hidden-lable");

		_numLink.click(function(){
			_numLink.removeClass("selected");
			$j(this).addClass("selected");
			var _letter = $j(this).children().text();
			_item.hide();
			_lable.each(function(){
				if ($j(this).text()== _letter ) {
					$j(this).parents("li").show();
					return;
				};
			});
			if (_letter == "All") {
				_lable.parents("li").show();
			}
			return false;
		})
	});
}



/*function initAlphbet(){
	var _hold = $j("div.alphaholder");
	_hold.each(function(){
		var _nav = $j("ul.alphanavigation");
		var _numLink = $j("li a", _nav);
		var _itemHold = $j("ul.alphalist");
		var _item = $j("> li", _itemHold);
		var _lable = $j(this).find("span.hidden-lable");

		
	});
}*/
function initExpandTextArea(){
	$j('div.comments textarea').each(function(){
		var _hold = $j(this).parents('div.comments:eq(0)');
		var _text = this.value;
		this.onfocus = function(){
			_hold.addClass('active-text');
			if(this.value == _text) this.value = '';
		}
		this.onblur = function(){
			if(this.value == '') this.value = _text;
		}
	});
}



function initMenu()
{
	var _nav = document.getElementById("nav");
	if (_nav) {
		var nodes = _nav.getElementsByTagName("li");
		for (var i=0; i<nodes.length; i++)
		{
			nodes[i].onmouseover = function()
			{
				if (this.className.indexOf('hover') == -1)
				this.className += " hover";
			}
			nodes[i].onmouseout = function()
			{
				this.className = this.className.replace(" hover", "");
			}
		}
	}
	var _log = document.getElementById("log");
	if (_log) {
		var nodes = _log.getElementsByTagName("li");
		for (var i=0; i<nodes.length; i++)
		{
			nodes[i].onmouseover = function()
			{
				if (this.className.indexOf('hover') == -1)
				this.className += " hover";
			}
			nodes[i].onmouseout = function()
			{
				this.className = this.className.replace(" hover", "");
			}
		}
	}
}
if (document.all && !window.opera) attachEvent("onload", initMenu);


function ClearText()
{
	var inputs = document.getElementsByTagName("input");
	for (var i=0; i<inputs.length; i++)
	{
		if (inputs[i].type == "text")
		{
			inputs[i].onfocus = function ()
			{
					if (this.value == "What would you like to say?")
						this.value = "";
					if (this.value == "Search TV and Movies...")
						this.value = "";
					if (this.value == "Search & Watch TV Shows - Movies")
						this.value = "";
					if (this.value == "Search and Watch TV shows")
						this.value = "";
					if (this.value == "Gossip")
						this.value = "";
					if (this.value == "Search and Listen to over 8 million songs")
						this.value = "";
					if (this.value == "Search real-time entertainment")
						this.value = "";
					if (this.value == "Search and Watch Movies")
						this.value = "";
					if (this.value == "Search and Learn about Celebrities")
						this.value = "";
					if (this.value == "Search and Watch Anime")
						this.value = "";	
			}
			inputs[i].onblur = function ()
			{
					if (this.value == "" && this.name == "search"){
						this.value = "What would you like to say?";
						
					}
					if (this.value == "" && this.name == "status_new2") this.value = "What would you like to say?";
					
					if (this.value == "" && this.name == "find") {
						this.value = "Search TV and Movies...";
						
					}
					if(this.name == "find")
					{
							$j('#ajax_listOfOptions').hide("slow");
							
					}
					if (this.value == "" && this.name == "search-content") this.value = "Search & Watch TV Shows - Movies";
					if (this.value == "" && this.name == "search-content2") this.value = "Search and Watch TV shows";
					if (this.value == "" && this.name == "search_form_value") this.value = "Search real-time entertainment";
					if (this.value == "" && this.name == "search-content-result") this.value = "Gossip";
					if (this.value == "" && this.name == "search-content-music") this.value = "Search and Listen to over 8 million songs";
					if (this.value == "" && this.name == "search-content-movie") this.value = "Search and Watch Movies";
					if (this.value == "" && this.name == "search-content-celebr") this.value = "Search and Learn about Celebrities";
					if (this.value == "" && this.name == "search-content-anime") this.value = "Search and Watch Anime";
			}
		}
		
	}
}



$j(document).ready(function initPage() {
	initTabs_rotator('div.tabs.video-banner','div.banner','ul.tabNavigation',true,5000);
	initTabs('div.tabs','div.tabs-holder','ul.tabNavigation');
	//initTabs('div.tabs-main','div.tabs-holder-main','ul.tabNavigation-main');
	initExpandTextArea();
	//initExpandOnToday();
	initAlphbet();
	ClearText();
	
	$j('#feedback_button').click(function() {
		window.open(
			'https://spreadsheets.google.com/spreadsheet/viewform?formkey=dGtEbmVUR1FpX3dZU3o3Si05c080WUE6MQ',
			'give_feedback',
			'status=0, toolbar=0, location=0, menubar=0, resizable=1, scrollbars=1, height=660, width=660'
		);
		return false;
	});	
});


function recommend_track(page_name,topic_name,value)
{
	_gaq.push(['_trackEvent', 'Recommendations', 'Clicked Recommendation on '+page_name,topic_name,value]);
}
function episode_not_available(id){	
	$j("#"+id).html("Sorry, this episode is currently not available online - please check back later.");
}
// Code for FB Facepile

var check_facepile_interval

// When loading, facepile is 70px or 0px high. Monitor it for changes in height.
$j(document).ready(function() {
	if ($j('.facepile-container').length > 0) {
		check_facepile_interval = setInterval("check_facepile()", 250);
	}
});


function check_facepile() {
	
	var facepile_height = $j('.facepile-container:first-child').children().innerHeight();
	
	if (facepile_height < 90 && facepile_height > 30) { // Height becomes about 59-62px when friends load
		
		clearInterval(check_facepile_interval);
		$j('.facepile-container').css('position', 'relative');
		$j('.facepile-container').css('height', 58);
		$j('.facepile-container').css('margin-top', 0);
		$j('.facepile-container').css('visibility', 'visible');
		
		// Reposition tooltips if visible
		if (show_favorite_tip) {
			$j('#favorite_tip').css('top', $j('.fav-btn').offset().top - 20);
		}
		if (show_notification_tip) {
			$j('#notification_tip').css('top', $j('#notification_statuses div:last').offset().top - 22);
		}
	}
}

// Code for Netflix connect in Account Settings

$j(document).ready(function() {
	
	if ($j('#netflix_question').length > 0) {
		// Check for radios being checked on page load.
		if ($j('#netflix_question #yes').is(':checked')) {
			if($j('#inline_netflix_subscription.content-box').length > 0) {
				show_netflix_connect($j('#inline_netflix_subscription').children());
			} else {
				show_netflix_connect($j(this));
			}
		} else if ($j('#netflix_question #no').is(':checked')) {
			if($j('#inline_netflix_subscription.content-box').length > 0) {
				show_netflix_signup($j('#inline_netflix_subscription').children());
			} else {
				show_netflix_signup($j(this));
			}
		}
	}
	
	$j('#netflix_question #yes').live('click', function() {
		$j('input#yes').attr('checked', true);
		if ($j(this).is(':checked')) {
			show_netflix_connect($j(this));
		}
	});
	
	$j('#netflix_question #no').live('click', function() {
		$j('input#no').attr('checked', true);
		if ($j(this).is(':checked')) {
			show_netflix_signup($j(this));
		}
	});
	
});

function show_netflix_connect(trigger) {
	
	if(trigger.parents('#netflix_subscription_generic, #netflix_subscription, #inline_netflix_subscription').length > 0) {
		$j('div#netflix_question').css('border-left', '1px solid #CCC');
	} else {
		$j('div#netflix_question').css('border-right', '1px solid #CCC');
	}
	
	$j('#netflix_signup').hide();
	$j('#netflix_connect').fadeIn(300);
	$j('.modal #netflix_signup').hide();
	$j('.modal #netflix_connect').fadeIn(300);
	
}

function show_netflix_signup(trigger) {
	
	if(trigger.parents('#netflix_subscription_generic, #netflix_subscription, #inline_netflix_subscription').length > 0) {
		$j('div#netflix_question').css('border-left', '1px solid #CCC');
	} else {
		$j('div#netflix_question').css('border-right', '1px solid #CCC');
	}
	
	$j('#netflix_connect').hide();
	$j('#netflix_signup').fadeIn(300);
	$j('.modal #netflix_connect').hide();
	$j('.modal #netflix_signup').fadeIn(300);
	
}

// Netflix Subscription Overlay
var netflix_connect_generic = 0; 
function bind_netflix_connect_generic(){
	if(globals.user_id >0){	
		$j.modal.close();											 
		window.open('/ajax_get_netflix_login_url.php',"mywindow","menubar=1,resizable=1,width=400,height=500");		
	}else{
		$j.modal.close();
		netflix_connect_generic = 1;	//set this flag because we need to redirect user on Netlfix page when user successfully login 
		show_login_overlay(); 
		qaq_google_stat('Netflix Overlay - Generic', 'Clicked "Login to yidio login overlay"');
	}
	return false;
}
function load_generic_overlay_netflix(){
	$j('#netflix_login_link_generic').live('click', function(event) {
		bind_netflix_connect_generic();
	});	
	$j('#netflix_start_free_trial_generic').live('click', function(event) {
		//$j.modal.close();
		set_netflix_stats_generic("Netflix Overlay - Generic","netflix_start_free_trial");
		qaq_google_stat('Netflix Overlay - Generic', 'Clicked "Start Netflix Trial"');			
	});

	$j('#netflix_subscription_generic #netflix_connect a').live('click', function() {
		qaq_google_stat('Netflix Overlay - Generic', 'Clicked "Netflix Connect"');
	});
	
	var netflix_account_generic = parseInt($j('#netflix_account_generic').val());
	if (netflix_account_generic == 1) {
		$j('#netflix_question #yes').click();
		show_netflix_connect($j('#netflix_subscription_generic').children());
	} else{
		$j('#netflix_question #no').click();
		show_netflix_signup($j('#netflix_subscription_generic').children());
	}
	if(globals.user_id >0){	
		var user_netflix = parseInt($j('#user_netflix_generic').val());
		var user_netflix_status = parseInt($j('#user_netflix_status').val());
		if(user_netflix == 1 && user_netflix_status == 0){
			$j('#netflix_fav_cancel_generic').unbind();
			$j('#netflix_fav_cancel_generic, #netflix_import_main_close_generic').click(function() {
				window.location = '/profile_netflix.php';//$j.modal.close();
			});	
			//Track add to favorite button clicked
			$j('#netflix_shows_generic .remove-show').live('click', function(event) {
				$j(this).parent().fadeOut(200);
			});
			$j('#netflix_import_generic #add_to_favorite_netflix_tvshows').live('click', function(event) {
				var i = 0;
				var t = 0;
				$j('#spinner_id_generic').show();
				$j('#netflix_shows_generic .clearfix').each(function() {
					if($j(this).css('display') != 'none'){
						
						var fav_row_href = $j(this).find('a').attr('href');
						var show_id = $j(this).children( '#show_id').val();
						var user_id= globals.user_id;
						$j.ajax({
							   type: "GET",
							   url: "/actions/store_onsingup_shows_favorites.php",
							   data: "userid="+user_id+"&id="+show_id,
							   success: function(response){
								   if($j('#total_netflix_tvshows').val() == i){
										window.location = '/profile_netflix.php';
									}
							   }
						});
					}else{
						t++;
					}
					i++;
				});
				if($j('#total_netflix_tvshows').val() == t){
					window.location = '/profile_netflix.php';
				}
				$j.modal.close();
			});		
		}
		return false;
	}else{
		return false;
	}
}
function set_netflix_stats_generic(action_page,action_type){
	$j.ajax( {
			type : "POST"
			, url : '/ajax_netflix_stats.php'
			, data : 'action_page='+action_page+'&action_type='+action_type
			, success : function (response) {
			}	
	});	
}
function save_netflix_tokens_generic(){
	var user_id= globals.user_id;
	var netflix_user_fullname = $j('#netflix_user_fullname_generic').val();
	var netflix_user_nickname = $j('#netflix_user_nickname_generic').val();
	var oauth_access_token = $j('#oauth_access_token_generic').val();
	var oauth_access_token_secret = $j('#oauth_access_token_secret_generic').val();
	var netflix_user_id = $j('#netflix_user_id_generic').val();
	var parameters = "userid="+user_id+"&netflix_user_fullname="+netflix_user_fullname+"&netflix_user_nickname="+netflix_user_nickname+"&oauth_access_token="+oauth_access_token+"&oauth_access_token_secret="+oauth_access_token_secret+"&netflix_user_id="+netflix_user_id;
	$j.ajax({  
			   type: "GET",
			   url: "/ajax_netflix_access_tokens.php",
			   data: parameters,
			   success: function(response){
			    	$j('#user_netflix_status').val('1');
			   }
		   });
}
function show_netflix_shows_generic(){
	$j('#netflix_shows_generic').html('<img alt="" src="/images/loading.gif" />');
	$j.ajax({
		   type: "GET",
		   url: "/ajax_get_netflix_tvshows.php",
		   data: '',
		   success: function(response){
				if(response.match('<div class="show clearfix">')) { 
					   $j('#netflix_shows_generic').html(response);				   
				}else{
				 	$j.modal.close();
			    }
		   }
	   });	
}
function give_credits_user_for_netflix_generic(){
	var user_id= globals.user_id;
	$j.ajax({
		   type: "GET",
		   url: "/ajax_give_credits_for_netflix.php",
		   data: "userid="+user_id,
		   success: function(response){
		   }
	});	
}
function show_netflix_favorites_generic(){
	save_netflix_tokens_generic();
	give_credits_user_for_netflix_generic();
	show_netflix_shows_generic();
	$j('#netflix_import_generic').css('width','475px');
	$j('#netflix_import_generic').modal({zIndex:999999999, persist:true});	
	set_netflix_stats_generic("Netflix Overlay - Generic","netflix_connect");
	qaq_google_stat('Netflix Overlay - Generic','Clicked "Netflix Connect"');
}
function generic_netflix_overlay(){
	qaq_google_stat('Netflix Overlay - Generic','Netflix Overlay Loaded');
	$j('#netflix_subscription_generic').css('width','700px');
	$j('#netflix_subscription_generic').modal({zIndex:999999999, persist:true, position:[120], opacity:70});
}
function qaq_google_stat(param1,param2){
	try{
		_gaq.push(['_trackEvent', param1, param2]);	
	}catch(e) {
		//nothing here
	}
}

$j(document).ready(function() {
	var myRegExp1 = /_admedia_|_adon|_jema|_1001/;
	if(!globals.header_all_utm_params)
		globals.header_all_utm_params = '';
	var utm_check_string = globals.header_all_utm_params.toLowerCase();
	if(utm_check_string.search(myRegExp1) == -1){
		$j.ajax({
			type : 'POST'
			, url : '/common_netflix_overlay_cookie.php'
			, dataType : 'html'
			, data : 'user_id='+ globals.user_id
			, success : function (contents) {
				if(contents != 0){
					
					$j('body').append(contents);
					
					var gwo_source; // object containing utmx section
					var gwo_target; // object being modified by contents of utmx section
					
					gwo_source = $j('#gen_netflix_titlebar');
					gwo_target = $j('#netflix_subscription_generic .title_center b');
					gwo_replace(gwo_source, gwo_target);
					
					gwo_source = $j('#gen_netflix_offer');
					gwo_target = $j('#netflix_subscription_generic #netflix_signup p b');
					gwo_replace(gwo_source, gwo_target);
					
					gwo_source = $j('#gen_netflix_trial');
					gwo_target = $j('#netflix_subscription_generic #netflix_signup a b');
					gwo_replace(gwo_source, gwo_target);

					load_generic_overlay_netflix();
					generic_netflix_overlay();
				}
			}			
		});			
	}
});

function gwo_replace(source, target) {
	var replacement_text = strip_utmx(source.text());
	if (replacement_text.length > 0) {
		target.text(replacement_text);
	}
}

function strip_utmx(str) {
	return str.substring(str.indexOf(')')+1, str.length);
}

/* Code to expand link hotspots */

$j(document).ready(function() {
	$j('#netflix_subscription_generic #netflix_signup').live('click', function() {
		window.open($j(this).children('a').attr('href'), 'netflix');
		qaq_google_stat('Netflix Overlay - Generic','Clicked "Start Netflix Trial"');
		_gaq.push(['gwo2._trackPageview', '/2286526385/goal']);
		return false;
	});
	
	$j('#inline_netflix_subscription #netflix_signup').live('click', function() {
		window.open($j(this).children('a').attr('href'), 'netflix');
		qaq_google_stat('Inline Netflix Subscription','Clicked "Start Netflix Trial"');
		return false;
	});
	
	$j('#netflix_subscription #netflix_signup').live('click', function() {
		window.open($j(this).children('a').attr('href'), 'netflix');
		qaq_google_stat('Netflix Subscription','Clicked "Start Netflix Trial"');
		return false;
	});
});

/* Event tracking for generic Netflix subscription overlay */

$j(document).ready(function() {
	$j('#netflix_subscription_generic #netflix_connect a').live('click', function() {
		qaq_google_stat('Netflix Overlay - Generic','Clicked "Netflix Connect"');
	});
	
	$j('#netflix_subscription_generic .simplemodal-close').live('click', function() {
		qaq_google_stat('Netflix Overlay - Generic','Clicked close generic overlay');
	});
});

/* Event tracking for inline Netflix subscription overlay */

$j(document).ready(function() {

	$j('#inline_netflix_subscription #netflix_connect a').live('click', function() {
		qaq_google_stat('Inline Netflix Subscription','Clicked "Netflix Connect"');
	});
	
});

/* start file autogrow.js */


/*
 * SocialEngineMods Javascript Library Lite v0.1
 * http://www.SocialEngineMods.Net
 *
 * Copyright SocialEngineMods.Net
 * This code is licensed GPL for use exclusively on SocialEngine sites
 *
 */





/* Extensions */


Function.prototype.bind = function(obj) {
  var method = this, temp = function() {
    return method.apply(obj, arguments)
  };
  return(temp);
}; 


/* SEMods */


SEMods = function () {};

/* SEMods TextAreaControl */


SEMods.TextAreaControl = function(object) {
    this.obj = object;
    this.obj.style['overflow'] = 'hidden';
    this.originalHeight = this.obj.getStyle('height').toInt();
    var updater = this.update.bind(this);
    object.addEvent("focus", this.onFocus.bind(this));
    object.addEvent("blur", this.onBlur.bind(this));
    this.update();
};

SEMods.TextAreaControl.prototype = {
    obj : null,
    updating : false,
    autoGrow : false,
    originalHeight : null,
    shadowElement : null,
    increment : 0,
    timer : null,
    lastLength : 0,
    
    setAutoGrow : function(autoGrow) {
        this.autoGrow = autoGrow;
        this.createShadowElement();
        this.update();
    },
    
    onUpdate : function() {
        if(this.autoGrow && this.lastLength != this.obj.value.length) {
            this.lastLength = this.obj.value.length;
            this.updateShadowElement();
            this.obj.style.height = Math.max(this.originalHeight, this.shadowElement.offsetHeight + this.increment) + 'px';
        }
    },
    
    beginUpdate : function() {
        if(this.updating)
            return false;
        this.updating = true;
        return true;
    },
    
    endUpdate : function() {
        this.updating = false;
    },
    
    update : function() {
        if(!this.beginUpdate())
            return;
        
        this.onUpdate();
        this.endUpdate();
    },
    
    createShadowElement : function() {
        if(this.shadowElement)
            return;
        
        this.shadowElement = document.createElement("DIV");
        this.shadowElement.style.position = "absolute";
        this.shadowElement.style.top = "-99999px";
        this.shadowElement.style.left = "-99999px";
        
        document.body.appendChild(this.shadowElement);
    },
    
    updateShadowElement : function () {
        if(this.shadowElement) {
	    text = this.obj.value+'<br>';
            this.shadowElement.innerHTML = text.toString().replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#039;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br />');
            var fontSize = this.getPXMetrics( this.obj.getStyle('font-size'), 10);
            var lineHeight = this.obj.getStyle('line-height');
            // Opera misses on line-height
            if((/Opera/i.test(navigator.userAgent))) 
              lineHeight = this.getPXMetrics( lineHeight, 0) + 3 + 'px';
              
            this.increment = fontSize + 10;
        
            this.shadowElement.style['width'] = this.obj.offsetWidth + 'px';
            this.shadowElement.style['lineHeight'] = lineHeight;
            this.shadowElement.style['fontSize'] = this.obj.getStyle('font-size');

            this.shadowElement.style['fontFamily'] = this.obj.getStyle('font-family');
            this.shadowElement.style['paddingLeft'] = this.obj.getStyle('padding-left');
            this.shadowElement.style['paddingRight'] = this.obj.getStyle('padding-right');
            
        } 
    },
    
    onFocus : function() {
      this.timer = setInterval(this.update.bind(this), 500);
    },
    
    onBlur : function() {
      if(this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },

    // em's not supported for now
    getPXMetrics : function(metric, defvalue) {
      var metricBase = parseFloat(metric);
      if(isNaN(metricBase)) return defvalue!=null ? defvalue : metricBase;
      return /px/i.test(metric) ? metricBase : /pt/i.test(metric) ? 1.3333*metricBase  : metricBase;
    }
    
};


/* Global namespace helper functions */


function textarea_autogrow(elementid) {
    var el = $(elementid);
//    if(!el) alert("textarea_autogrow(): element not found");
    if(el && !el._controlled) {
        el._controlled = true;
        new SEMods.TextAreaControl(el).setAutoGrow(true);
	return el.getStyle('height').toInt();
    }
};


/* end file autogrow.js 
start file  smoothbox.js */


/*
 * Smoothbox v20080623 by Boris Popoff (http://gueschla.com)
 * To be used with mootools 1.2
 *
 * Based on Cody Lindley's Thickbox, MIT License
 *
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

/*start file thickbox.js */

/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
	
	
	
var tb_pathToImage = "http://img1.yidio.com/social/images/loadingAnimation.gif";

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call tb_init
$j(document).ready(function(){   
	tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;
});

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
	$j(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	tb_show(t,a,g);
	this.blur();
	return false;
	});
}

function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link

	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$j("body","html").css({height: "100%", width: "100%"});
			$j("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$j("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$j("#TB_overlay").click(tb_remove);
			}
		}else{//all others
			if(document.getElementById("TB_overlay") === null){
				$j("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$j("#TB_window").css({display:"none"});
				$j("#TB_overlay").click(tb_remove);
			}
		}
		
		if(tb_detectMacXFF()){
			$j("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$j("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$j("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$j('#TB_load').show();//show loader
		
		var baseURL;
	   if(url.indexOf("?")!==-1){ //ff there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
	   }else{ 
	   		baseURL = url;
	   }
	   
	   var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
	   var urlType = baseURL.toLowerCase().match(urlString);

		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
				
			TB_PrevCaption = "";
			TB_PrevURL = "";
			TB_PrevHTML = "";
			TB_NextCaption = "";
			TB_NextURL = "";
			TB_NextHTML = "";
			TB_imageCount = "";
			TB_FoundURL = false;
			if(imageGroup){
				TB_TempArray = $j("a[@rel="+imageGroup+"]").get();
				for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
					var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
						if (!(TB_TempArray[TB_Counter].href == url)) {						
							if (TB_FoundURL) {
								TB_NextCaption = TB_TempArray[TB_Counter].title;
								TB_NextURL = TB_TempArray[TB_Counter].href;
								TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
							} else {
								TB_PrevCaption = TB_TempArray[TB_Counter].title;
								TB_PrevURL = TB_TempArray[TB_Counter].href;
								TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
							}
						} else {
							TB_FoundURL = true;
							TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);											
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = tb_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing
			
			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			$j("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a></div>"); 		
			
			$j("#TB_closeWindowButton").click(tb_remove);
			
			if (!(TB_PrevHTML === "")) {
				function goPrev(){
					if($j(document).unbind("click",goPrev)){$j(document).unbind("click",goPrev);}
					$j("#TB_window").remove();
					$j("body").append("<div id='TB_window'></div>");
					tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
					return false;	
				}
				$j("#TB_prev").click(goPrev);
			}
			
			if (!(TB_NextHTML === "")) {		
				function goNext(){
					$j("#TB_window").remove();
					$j("body").append("<div id='TB_window'></div>");
					tb_show(TB_NextCaption, TB_NextURL, imageGroup);				
					return false;	
				}
				$j("#TB_next").click(goNext);
				
			}

			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				} else if(keycode == 190){ // display previous image
					if(!(TB_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(TB_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			tb_position();
			$j("#TB_load").remove();
			$j("#TB_ImageOff").click(tb_remove);
			$j("#TB_window").css({display:"block"}); //for safari using css instead of show
			};
			
			imgPreloader.src = url;
		}else{//code to show html
			
			var queryString = url.replace(/^[^\?]+\??/,'');
			var params = tb_parseQuery( queryString );

			TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
			TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = TB_WIDTH - 30;
			ajaxContentH = TB_HEIGHT - 45;
			
			if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window		
					urlNoQuery = url.split('TB_');
					$j("#TB_iframeContent").remove();
					if(params['modal'] != "true"){//iframe no modal
						$j("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
					}else{//iframe modal
					$j("#TB_overlay").unbind();
						$j("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
					}
			}else{// not an iframe, ajax
					if($j("#TB_window").css("display") != "block"){
						if(params['modal'] != "true"){//ajax no modal
						$j("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
						}else{//ajax modal
						$j("#TB_overlay").unbind();
						$j("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");	
						}
					}else{//this means the window is already up, we are just loading new content via ajax
						$j("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
						$j("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
						$j("#TB_ajaxContent")[0].scrollTop = 0;
						$j("#TB_ajaxWindowTitle").html(caption);
					}
			}
					
			$j("#TB_closeWindowButton").click(tb_remove);
			
				if(url.indexOf('TB_inline') != -1){	
					$j("#TB_ajaxContent").append($j('#' + params['inlineId']).children());
					$j("#TB_window").unload(function () {
						$j('#' + params['inlineId']).append( $j("#TB_ajaxContent").children() ); // move elements back when you're finished
					});
					tb_position();
					$j("#TB_load").remove();
					$j("#TB_window").css({display:"block"}); 
				}else if(url.indexOf('TB_iframe') != -1){
					tb_position();
					if($.browser.safari){//safari needs help because it will not fire iframe onload
						$j("#TB_load").remove();
						$j("#TB_window").css({display:"block"});
					}
				}else{
					$j("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						tb_position();
						$j("#TB_load").remove();
						tb_init("#TB_ajaxContent a.thickbox");
						$j("#TB_window").css({display:"block"});
					});
				}
			
		}

		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				}	
			};
		}
		
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function tb_showIframe(){
	$j("#TB_load").remove();
	$j("#TB_window").css({display:"block"});
}

function tb_remove() {
 	$j("#TB_imageOff").unbind("click");
	$j("#TB_closeWindowButton").unbind("click");
	$j("#TB_window").fadeOut("fast",function(){$j('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
	$j("#TB_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$j("body","html").css({height: "auto", width: "auto"});
		$j("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}

function tb_position() {
	var winWidth = $j(window).width(); 
	var winHeight  = $j(window).height(); 
	var scrollbar = $j(window).scrollTop();
        /*$j("#TB_window").css({Left: '467px', width: TB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$j("#TB_window").css({Top: '88px'});
	}*/
    var centerDiv = $j('#TB_window'); 
	centerDiv.css('top', winHeight/2-centerDiv.height()/2); 
	centerDiv.css('left', winWidth/2-centerDiv.width()/2); 
	$j('#TB_overlay').css({opacity:0.6,height:winHeight+'px',width:winWidth+'px'});
	$j(window).scrollTop(0);
	//alert('scroll top position : '+$j(window).scrollTop());
}

function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function tb_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}

function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}


/* end file thickbox.js
start file autosuggest.js */



/**
 *  author:		Timothy Groves - http://www.brandspankingnew.net
 *	version:	1.2 - 2006-11-17
 *              1.3 - 2006-12-04
 *              2.0 - 2007-02-07
 *              2.1.1 - 2007-04-13
 *              2.1.2 - 2007-07-07
 *              2.1.3 - 2007-07-19
 *
 */


if (typeof(bsn) == "undefined")
	_b = bsn = {};


if (typeof(_b.Autosuggest) == "undefined")
	_b.Autosuggest = {};












_b.AutoSuggest = function (id, param)
{
	// no DOM - give up!
	//
	if (!document.getElementById)
		return 0;
	
	
	
	
	// get field via DOM
	//
	this.fld = _b.DOM.gE(id);

	if (!this.fld)
		return 0;
	
	
	
	
	// init variables
	//
	this.sInp 	= "";
	this.nInpC 	= 0;
	this.aSug 	= [];
	this.iHigh 	= 0;
	
	
	
	
	// parameters object
	//
	this.oP = param ? param : {};
	
	// defaults	
	//
	var k, def = {minchars:1, meth:"get", varname:"input", className:"autosuggest", timeout:2500, delay:0, offsety:-5, shownoresults: true, noresults: "No results!", maxheight: 250, cache: true, maxentries: 25, blurtrigger: false, multisuggest: true};
	for (k in def)
	{
		if (typeof(this.oP[k]) != typeof(def[k]))
			this.oP[k] = def[k];
	}
	
	
	// set keyup handler for field
	// and prevent autocomplete from client
	//
	var p = this;
	
	// NOTE: not using addEventListener because UpArrow fired twice in Safari
	//_b.DOM.addEvent( this.fld, 'keyup', function(ev){ return pointer.onKeyPress(ev); } );
	
	this.fld.onkeypress 	= function(ev){ return p.onKeyPress(ev); };
	this.fld.onkeyup 	= function(ev){ return p.onKeyUp(ev); };
	if (typeof(this.oP.callback) == "function" && this.oP.blurtrigger) {
	  this.fld.onblur = function(event) { 
		if(document.activeElement && typeof(event) === "undefined") { 
			var targetFocus = document.activeElement;
		} else {
			var targetFocus = event.explicitOriginalTarget;
			while(targetFocus.parentNode) {
			  if(targetFocus.tagName == 'A' && typeof(targetFocus.id) == 'string') { if(targetFocus.id.substring(0, 10) == 'bsnsuggest') { break; } }
			  targetFocus = targetFocus.parentNode;
			}
			if(typeof(targetFocus.id) != 'string') { targetFocus.id = ''; }
		}
		if(targetFocus.id.substring(0, 10) != 'bsnsuggest') {
		  p.oP.callback( {id:p.fld.value, value: p.fld.value} ); 
		  p.clearSuggestions();
		}
	  }
	}
	
	this.fld.setAttribute("autocomplete","off");
};
















_b.AutoSuggest.prototype.onKeyPress = function(ev)
{
	
	var key = (window.event) ? window.event.keyCode : ev.keyCode;



	// set responses to keydown events in the field
	// this allows the user to use the arrow keys to scroll through the results
	// ESCAPE clears the list
	// TAB sets the current highlighted value
	//
	var RETURN = 13;
	var TAB = 9;
	var ESC = 27;
	var SEMICOLON = 186;
	
	var bubble = 1;

	switch(key)
	{
		case RETURN:
			if(this.aSug.length != 0 && this.iHigh) {
				this.setHighlightedValue();
				bubble = false;
			} else {
				if(this.fld.value.length > 0) {
					if (typeof(this.oP.callback) == "function") {
						this.clearSuggestions();
						this.oP.callback( {id:this.fld.value, value: this.fld.value} );
					}
					bubble = false;
				} else  {
					bubble = false;
				}
				
			}
			break;

		case ESC:
			this.clearSuggestions();
			break;
				
	}

	return bubble;
};



_b.AutoSuggest.prototype.onKeyUp = function(ev)
{
	var key = (window.event) ? window.event.keyCode : ev.keyCode;
	


	// set responses to keydown events in the field
	// this allows the user to use the arrow keys to scroll through the results
	// ESCAPE clears the list
	// TAB sets the current highlighted value
	//

	var ARRUP = 38;
	var ARRDN = 40;
	
	var bubble = 1;

	switch(key)
	{


		case ARRUP:
			this.changeHighlight(key);
			bubble = 0;
			break;


		case ARRDN:
			this.changeHighlight(key);
			bubble = 0;
			break;
		
		
		default:
			//this.getSuggestions(this.fld.value);
			// ADDED BY WEBLIGO
			var new_value = this.fld.value.split(/[;]+/ig);
			this.getSuggestions(new_value[new_value.length-1]);
	}

	return bubble;
	

};








_b.AutoSuggest.prototype.getSuggestions = function (val)
{
	
	// if input stays the same, do nothing
	//
	if (val == this.sInp)
		return 0;
	
	
	// kill list
	//
	_b.DOM.remE(this.idAs);
	
	
	this.sInp = val;
	
	
	// input length is less than the min required to trigger a request
	// do nothing
	//
	if (val.length < this.oP.minchars)
	{
		this.aSug = [];
		this.nInpC = val.length;
		return 0;
	}
	
	
	
	
	var ol = this.nInpC; // old length
	this.nInpC = val.length ? val.length : 0;
	
	
	
	// if caching enabled, and user is typing (ie. length of input is increasing)
	// filter results out of aSuggestions from last request
	//
	var l = this.aSug.length;
		if (this.nInpC > ol && l && l<this.oP.maxentries && this.oP.cache)
	{
		var arr = [];
		for (var i=0;i<l;i++)
		{
			if (this.aSug[i].value.substr(0,val.length).toLowerCase() == val.toLowerCase() || this.aSug[i].info.substr(0,val.length).toLowerCase() == val.toLowerCase()) {
				arr.push( this.aSug[i] );
			}
		}
		this.aSug = arr;
		
		// ADDED BY WEBLIGO
		if(this.aSug.length < l) {
			var pointer = this;
			var input = this.sInp;
			clearTimeout(this.ajID);
			this.ajID = setTimeout( function() { pointer.doAjaxRequest(input) }, this.oP.delay );
		} else {
			this.createList(this.aSug);
		}
		
		return false;
	}
	else
	// do new request
	//
	{
		var pointer = this;
		var input = this.sInp;
		clearTimeout(this.ajID);
		this.ajID = setTimeout( function() { pointer.doAjaxRequest(input) }, this.oP.delay );
	}

	return false;
};





_b.AutoSuggest.prototype.doAjaxRequest = function (input)
{
	// check that saved input is still the value of the field
	// CHANGED BY WEBLIGO
	var new_value = this.fld.value.split(/[;]+/ig);
	if (input != new_value[new_value.length-1])
		return false;
	
	
	
	var pointer = this;
	
	
	// create ajax request
	//
	if (typeof(this.oP.script) == "function")
		var url = this.oP.script(encodeURIComponent(this.sInp));
	else
		var url = this.oP.script+this.oP.varname+"="+encodeURIComponent(this.sInp);
	
	if (!url)
		return false;
	
	var meth = this.oP.meth;
	var input = this.sInp;
	
	var onSuccessFunc = function (req) { pointer.setSuggestions(req, input) };
	var onErrorFunc = function (status) {  };

	var myAjax = new _b.Ajax();
	myAjax.makeRequest( url, meth, onSuccessFunc, onErrorFunc );
};





_b.AutoSuggest.prototype.setSuggestions = function (req, input)
{
	// if field input no longer matches what was passed to the request
	// don't show the suggestions
	// CHANGED BY WEBLIGO
	var new_value = this.fld.value.split(/[;]+/ig);
	if (input != new_value[new_value.length-1])
		return false;
	
	this.aSug = [];
	
	
	if (this.oP.json)
	{
		var jsondata = eval('(' + req.responseText + ')');
		
		for (var i=0;i<jsondata.results.length;i++)
		{
			// CHANGED BY WEBLIGO
			this.aSug.push(  { 'id':jsondata.results[i].id, 'value':jsondata.results[i].value, 'info':jsondata.results[i].info, 'photo':jsondata.results[i].photo, 'photo_width':jsondata.results[i].photo_width }  );
		}
	}
	else
	{

		var xml = req.responseXML;
	
		// traverse xml
		//
		var results = xml.getElementsByTagName('results')[0].childNodes;

		for (var i=0;i<results.length;i++)
		{
			if (results[i].hasChildNodes())
				this.aSug.push(  { 'id':results[i].getAttribute('id'), 'value':results[i].childNodes[0].nodeValue, 'info':results[i].getAttribute('info') }  );
		}
	
	}
	
	this.idAs = "as_"+this.fld.id;
	

	this.createList(this.aSug);

};














_b.AutoSuggest.prototype.createList = function(arr)
{
	var pointer = this;
	
	
	
	
	// get rid of old list
	// and clear the list removal timeout
	//
	_b.DOM.remE(this.idAs);
	this.killTimeout();
	
	
	// if no results, and shownoresults is false, do nothing
	//
	if (arr.length == 0 && !this.oP.shownoresults) 
		return false;
	
	
	// create holding div
	//
	var div = _b.DOM.cE("div", {id:this.idAs, className:this.oP.className});	
	
	var hcorner = _b.DOM.cE("div", {className:"as_corner"});
	var hbar = _b.DOM.cE("div", {className:"as_bar"});
	var header = _b.DOM.cE("div", {className:"as_header"});
	header.appendChild(hcorner);
	header.appendChild(hbar);
	div.appendChild(header);
	
	
	
	
	// create and populate ul
	//
	var ul = _b.DOM.cE("ul", {id:"as_ul"});
	
	
	
	
	// loop throught arr of suggestions
	// creating an LI element for each suggestion
	//
	for (var i=0;i<arr.length;i++)
	{
		// format output with the input enclosed in a EM element
		// (as HTML, not DOM)
		//
		var val = arr[i].value;
		var val2 = arr[i].info;
		var st = val.toLowerCase().indexOf( this.sInp.toLowerCase() );
		var st2 = val2.toLowerCase().indexOf( this.sInp.toLowerCase() );
		
		if(st != -1) {
			var output = val.substring(0,st) + "<em>" + val.substring(st, st+this.sInp.length) + "</em>" + val.substring(st+this.sInp.length);
			var output2 = val2;
		} else {
			var output = val;
			var output2 = val2.substring(0,st2) + "<em>" + val2.substring(st, st2+this.sInp.length) + "</em>" + val2.substring(st2+this.sInp.length);
		}
		
		if (val != val2) {
			output = output2+" ("+output+")";
		}
		
		var span 		= _b.DOM.cE("span", {}, output, true);
		
		// CHANGED BY WEBLIGO
		var image		= _b.DOM.cE("img", {src:arr[i].photo, width: arr[i].photo_width, border:"0"});
		image.removeAttribute("height");
		span.insertBefore(image, span.childNodes[0]);

		var a 			= _b.DOM.cE("a", { href:"javascript:void(0);" });
		
		var tl 		= _b.DOM.cE("span", {className:"tl"}, " ");
		var tr 		= _b.DOM.cE("span", {className:"tr"}, " ");
		a.appendChild(tl);
		a.appendChild(tr);
		
		a.appendChild(span);
		
		a.name = i+1;
		a.id = 'bsnsuggest_'+(i+1);
		a.onclick = function () { pointer.setHighlightedValue(); return false; };
		a.onmouseover = function () { pointer.setHighlight(this.name); };
		
		var li = _b.DOM.cE(  "li", {}, a  );
		
		ul.appendChild( li );
	}
	
	
	// no results
	//
	if (arr.length == 0 && this.oP.shownoresults)
	{
		var li = _b.DOM.cE(  "li", {className:"as_warning"}, this.oP.noresults  );
		ul.appendChild( li );
	}
	
	
	div.appendChild( ul );
	
	var fcorner = _b.DOM.cE("div", {className:"as_corner"});
	var fbar = _b.DOM.cE("div", {className:"as_bar"});
	var footer = _b.DOM.cE("div", {className:"as_footer"});
	footer.appendChild(fcorner);
	footer.appendChild(fbar);
	div.appendChild(footer);
	
	
	
	// get position of target textfield
	// position holding div below it
	// set width of holding div to width of field
	//
	var pos = _b.DOM.getPos(this.fld);
	
	div.style.left 		= pos.x + "px";
	div.style.top 		= ( pos.y + this.fld.offsetHeight + this.oP.offsety ) + "px";
	div.style.width 	= this.fld.offsetWidth + "px";
	
	
	
	// set mouseover functions for div
	// when mouse pointer leaves div, set a timeout to remove the list after an interval
	// when mouse enters div, kill the timeout so the list won't be removed
	//
	div.onmouseover 	= function(){ pointer.killTimeout() };
	div.onmouseout 		= function(){ pointer.resetTimeout() };


	// add DIV to document
	//
	document.getElementsByTagName("body")[0].appendChild(div);
	
	
	
	// currently no item is highlighted
	//
	this.iHigh = 0;
	
	
	
	
	
	
	// remove list after an interval
	//
	var pointer = this;
	this.toID = setTimeout(function () { pointer.clearSuggestions() }, this.oP.timeout);
};















_b.AutoSuggest.prototype.changeHighlight = function(key)
{	
	var list = _b.DOM.gE("as_ul");
	if (!list)
		return false;
	
	var n;

	if (key == 40)
		n = this.iHigh + 1;
	else if (key == 38)
		n = this.iHigh - 1;
	
	
	if (n > list.childNodes.length)
		n = list.childNodes.length;
	if (n < 1)
		n = 1;
	
	
	this.setHighlight(n);
};



_b.AutoSuggest.prototype.setHighlight = function(n)
{
	var list = _b.DOM.gE("as_ul");
	if (!list)
		return false;
	
	if (this.iHigh > 0)
		this.clearHighlight();
	
	this.iHigh = Number(n);
	
	list.childNodes[this.iHigh-1].className = "as_highlight";


	this.killTimeout();
};


_b.AutoSuggest.prototype.clearHighlight = function()
{
	var list = _b.DOM.gE("as_ul");
	if (!list)
		return false;
	
	if (this.iHigh > 0)
	{
		list.childNodes[this.iHigh-1].className = "";
		this.iHigh = 0;
	}
};


_b.AutoSuggest.prototype.setHighlightedValue = function ()
{
	if (this.iHigh)
	{
		// CHANGED BY WEBLIGO
		var all_values = this.fld.value.split(/[;]+/ig);
		all_values.pop();
		all_values.push(this.aSug[ this.iHigh-1 ].value);
		if(this.oP['multisuggest']) { var semicolon = ';'; } else { var semicolon = ''; }
		this.sInp = this.fld.value = all_values.join(';')+semicolon;
		
		// move cursor to end of input (safari)
		//
		this.fld.focus();
		if (this.fld.selectionStart)
			this.fld.setSelectionRange(this.sInp.length, this.sInp.length);
		

		// pass selected object to callback function, if exists
		//
		if (typeof(this.oP.callback) == "function")
			this.oP.callback( this.aSug[this.iHigh-1] );
			
			
		this.clearSuggestions();
	}
};













_b.AutoSuggest.prototype.killTimeout = function()
{
	clearTimeout(this.toID);
};

_b.AutoSuggest.prototype.resetTimeout = function()
{
	clearTimeout(this.toID);
	var pointer = this;
	this.toID = setTimeout(function () { pointer.clearSuggestions() }, 1000);
};







_b.AutoSuggest.prototype.clearSuggestions = function ()
{
	
	this.killTimeout();
	this.aSug 	= [];
	var ele = _b.DOM.gE(this.idAs);
	var pointer = this;
	if (ele)
	{
		var fade = new _b.Fader(ele,1,0,250,function () { _b.DOM.remE(pointer.idAs) });
	}
};










// AJAX PROTOTYPE _____________________________________________


if (typeof(_b.Ajax) == "undefined")
	_b.Ajax = {};



_b.Ajax = function ()
{
	this.req = {};
	this.isIE = false;
};



_b.Ajax.prototype.makeRequest = function (url, meth, onComp, onErr)
{
	
	if (meth != "POST")
		meth = "GET";
	
	this.onComplete = onComp;
	this.onError = onErr;
	
	var pointer = this;
	
	// branch for native XMLHttpRequest object
	if (window.XMLHttpRequest)
	{
		this.req = new XMLHttpRequest();
		this.req.onreadystatechange = function () { pointer.processReqChange() };
		this.req.open("GET", url, true); //
		this.req.send(null);
	// branch for IE/Windows ActiveX version
	}
	else if (window.ActiveXObject)
	{
		this.req = new ActiveXObject("Microsoft.XMLHTTP");
		if (this.req)
		{
			this.req.onreadystatechange = function () { pointer.processReqChange() };
			this.req.open(meth, url, true);
			this.req.send();
		}
	}
};


_b.Ajax.prototype.processReqChange = function()
{
	
	// only if req shows "loaded"
	if (this.req.readyState == 4) {
		// only if "OK"
		if (this.req.status == 200)
		{
			this.onComplete( this.req );
		} else {
			this.onError( this.req.status );
		}
	}
};










// DOM PROTOTYPE _____________________________________________


if (typeof(_b.DOM) == "undefined")
	_b.DOM = {};



/* create element */
_b.DOM.cE = function ( type, attr, cont, html )
{
	var ne = document.createElement( type );
	if (!ne)
		return 0;
		
	
	for (var a in attr) 
		ne[a] = attr[a];

	var t = typeof(cont);
	
	if (t == "string" && !html)
		ne.appendChild( document.createTextNode(cont) );
	else if (t == "string" && html)
		ne.innerHTML = cont;
	else if (t == "object")
		ne.appendChild( cont );

	return ne;
};



/* get element */
_b.DOM.gE = function ( e )
{
	var t=typeof(e);
	if (t == "undefined")
		return 0;
	else if (t == "string")
	{
		var re = document.getElementById( e );
		if (!re)
			return 0;
		else if (typeof(re.appendChild) != "undefined" )
			return re;
		else
			return 0;
	}
	else if (typeof(e.appendChild) != "undefined")
		return e;
	else
		return 0;
};



/* remove element */
_b.DOM.remE = function ( ele )
{
	var e = this.gE(ele);
	
	if (!e)
		return 0;
	else if (e.parentNode.removeChild(e))
		return true;
	else
		return 0;
};



/* get position */
_b.DOM.getPos = function ( e )
{
	var e = this.gE(e);

	var obj = e;

	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	
	var obj = e;
	
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;

	return {x:curleft, y:curtop};
};










// FADER PROTOTYPE _____________________________________________



if (typeof(_b.Fader) == "undefined")
	_b.Fader = {};





_b.Fader = function (ele, from, to, fadetime, callback)
{	
	if (!ele)
		return 0;
	
	this.e = ele;
	
	this.from = from;
	this.to = to;
	
	this.cb = callback;
	
	this.nDur = fadetime;
		
	this.nInt = 50;
	this.nTime = 0;
	
	var p = this;
	this.nID = setInterval(function() { p._fade() }, this.nInt);
};




_b.Fader.prototype._fade = function()
{
	this.nTime += this.nInt;
	
	var ieop = Math.round( this._tween(this.nTime, this.from, this.to, this.nDur) * 100 );
	var op = ieop / 100;
	
	if (this.e.filters) // internet explorer
	{
		try
		{
			this.e.filters.item("DXImageTransform.Microsoft.Alpha").opacity = ieop;
		} catch (e) { 
			// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
			this.e.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+ieop+')';
		}
	}
	else // other browsers
	{
		this.e.style.opacity = op;
	}
	
	
	if (this.nTime == this.nDur)
	{
		clearInterval( this.nID );
		if (this.cb != undefined)
			this.cb();
	}
};



_b.Fader.prototype._tween = function(t,b,c,d)
{
	return b + ( (c-b) * (t/d) );
};



/* end file autosuggest.js
start file sprintf.js */


/**
 * sprintf() for JavaScript v.0.4
 *
 * Copyright (c) 2007 Alexandru Marasteanu <http://alexei.417.ro/>
 * Thanks to David Baird (unit test and patch).
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 */

function str_repeat(i, m) { for (var o = []; m > 0; o[--m] = i); return(o.join('')); }

function sprintf()
{
  var i = 0, a, f = arguments[i++], o = [], m, p, c, x;
  while (f) {
    if (m = /^[^\x25]+/.exec(f)) o.push(m[0]);
    else if (m = /^\x25{2}/.exec(f)) o.push('%');
    else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
      if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) throw("Too few arguments.");
      if (/[^s]/.test(m[7]) && (typeof(a) != 'number'))
        throw("Expecting number but found " + typeof(a));
      switch (m[7]) {
        case 'b': a = a.toString(2); break;
        case 'c': a = String.fromCharCode(a); break;
        case 'd': a = parseInt(a); break;
        case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break;
        case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break;
        case 'o': a = a.toString(8); break;
        case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break;
        case 'u': a = Math.abs(a); break;
        case 'x': a = a.toString(16); break;
        case 'X': a = a.toString(16).toUpperCase(); break;
      }
      a = (/[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a);
      c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
      x = m[5] - String(a).length;
      p = m[5] ? str_repeat(c, x) : '';
      o.push(m[4] ? a + p : p + a);
    }
    else throw ("Huh ?!");
    f = f.substring(m[0].length);
  }
  return o.join('');
}

/* end file sprintf.js
start file   functions.js */


$j(document).ready(function() {
  var _w=0;
  $j('.search-result .rel-videos ul .txt-box .txt-inner').each(function(){
    if($j(this).height()>_w){
      _w=$j(this).height();
    }
  });
//  alert('w:'+_w);
 if(_w>0){
    $j('.search-result .rel-videos ul .txt-box .txt-inner').each(function(){
      $j(this).height(_w);
    });
  }
});
// here search f

function URLDecode(encodedString){
  encodedString = encodedString.toString();
  var x=0;
  var _len = encodedString.length;
  var _new_string='';
  while( x < _len ){

    if( encodedString.charCodeAt(x) == 37 && x < _len - 2 && encodedString.substr( x+1 , 2).search(/[a-f0-9]{2}/i) == 0){
      var _hex = encodedString.substr(x+1,2);
    var _dehex = String.fromCharCode('0x'+_hex);
    _new_string+=_dehex;
    x+=2;
    }else{
      _new_string+=encodedString.substr(x,1);
  }
  x++;
  }
  _new_string = _new_string.replace(/\+/g,' ');
  return _new_string;
}

function URLEncode(clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString().replace(/ /g,'+');
  var regex = /(^[a-zA-Z0-9+_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
      output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

function ucfirst (str) {
  
  str += '';
  str = str.toLowerCase();
  var str_arr = str.split(' ');
  var str_ret = '';
  for( var i=0;i<str_arr.length;i++){
    var str_i = str_arr[i];
    var f = str_i.charAt(0).toUpperCase();
    str_ret+= f + str_i.substr(1)+(i<str_arr.length-1?' ':'');
  }
  return str_ret;
}


function doSearchSmall(){
  var _term = $j('#search-small-box').val();
  if(_term.length >= 3 ){
    _term = URLEncode(_term);
    $j('#search-form-small').attr('action','/search/entertaiment/' + _term );
    $j('#search-form-small').submit();

  }else{
    alert('min 3 chars');
  }
  return void(0);
}
function doSearchById(term,sfid){
  var _term = term || false;
  if( _term === false ){
    var _form = $j('#'+sfid)[0];
    _term = $j(".dosearch",_form).val();
  }
  if(_term.length >= 3 ){
    _term = URLEncode(_term);
     $j('#'+sfid).attr('action','/search/entertaiment/' + _term );
     $j('#'+sfid).submit();
   }else{
     alert('min 3 chars');
   }
   return void(0);
}

function doSearchPage(page){
  
  var _loc_split = document.location.href.split('/');

  var _term = _loc_split[5];
  doSearch(URLDecode(_term),page);
  return void(0);
}
  
function doSearchBtn(form_id,type){
	
  var _type = type || false;
  var _form = $j('#'+form_id)[0];
  var search_text;
  if(type == 'search-top-form')
  	search_text = $j(".dosearch",_form).val();
  else if(type == 'all')
  	search_text = $j(".dosearch",_form).val();
  else
  {
	  search_text = $j(".dosearch2",_form).val();
  }
  
  if(search_text == "Find Entertainment..." || search_text=='Search & Watch TV Shows - Movies' || search_text=='Search and Watch TV shows' || search_text=='Search and Watch Movies' || search_text=='Search and Watch Anime' || search_text=='Search TV and Movies...' )
  	return false;
  //return doSearchById(false,form_id);
  return doSearch(false,1,_type,_form);
}
function doSearch(term,page,type,form){
  	
  var page = page || 1;
  var term = term || false;
  var form = form || false;
	
  var _type = type || false;
  if(_type === false){
		_type = $j('input[name="search_type"]:checked').val();
	  $j('input[name="search_type"]:checked').attr('checked','');
	}
  if(_type == 'show' ){
    var type = 'shows';
  } else if(_type == 'music' ){
    var type = 'music';
  } else if(_type == 'movie' ){
    var type = 'movies';
  } else if(_type == 'people' ){
    var type = 'artists';
  }else{
    var type = 'entertaiment';
  }
//  $j('#search-top-box').curtain();
  if( term === false ){
    if(form === false){
      term = $j("#bigsearchbox2").val();
    }else{
		
      term = $j("#search").val();
    }

	if(term == undefined)
	 term = $j(".dosearch",form).val();
	 if(term == 'Find Entertainment...')
	 term = $j(".dosearch2",form).val();
  }
  
if(redirected == 0)
{
  if(term.length > 0){
	  
    var _term = URLEncode(term);
	
    var _action = '/search/' + type + '/' + _term + '/' + page+ '?find=' +_term ;

    if(form === false){
      var _form = $j('#search-form')[0];
    }else{
      _form = form;
    }
	if(_form == undefined)
	 _form = $j('#search-top-form')[0];
    $j(_form).attr('action',_action);
	$j(_form).attr('method','post');
//    alert('act:'+_action);
    $j(_form).submit();
  }else{
//    $j('#search-top-box').curtain("remove");
    alert('empty query');
  }
}
  return void(0);
}

function fixEnter(field,e,small,type,sfid){
	
  var keynum;
  var keychar;
  var numcheck;
  var _small = small || false;
	var _type = type || false;
  var _sfid = sfid || false;
  if(window.event){
    keynum = e.keyCode;
  }else if(e.which){
    keynum = e.which;
  }
 //alert(_sfid);
//return false;
  keychar = String.fromCharCode(keynum);
  var _input_value = field.value;
//  alert(_input_value);
//  if(keynum==13 && document.getElementById("input-box-main").value.length == 0 ){
  if(keynum==13 && (_input_value.length == 0 || _input_value =="Find Entertainment...") ){
					
    return false;
  }else if(keynum==13){
	  
	 // doSearchBtn('search-top-form','all')
    if(_small===false){
		
      doSearch(_input_value,1,_type);
	 
    }else if(_small===true){
      doSearchSmall(_input_value);
	  
	 
    }else if(_sfid!==false&&_small==2){
		//doSearchBtn('search-top-form','all')
      doSearch(_input_value,1,_type);
	  
	 
    }
	
    return false;
  }


  return true;
}





/* end file functions.js 
start file tvmusics.js */


  var tube_hostname = location.hostname;

    var link_buffer = '';

    function open_album(link_name, season_number, keep_visible)

    {

        var episode_block = '#episode_' + link_name + '_' + season_number;

		//alert('http://' + tube_hostname + '/actions/link_list_musics.php?l=' + escape(link_name) + '&s=' + escape(season_number));

        if ($j(episode_block + ":visible").length == 1 && keep_visible == false)

        {

            $j(episode_block).hide();

        }

        else

        {

			

            $j(episode_block).show();

            $j(episode_block).html('<img src=/images/loader.gif>');

            $j.ajax({ type: "POST",

                url: 'http://' + tube_hostname + '/actions/link_list_musics.php',

                data: 'l=' + escape(link_name) + '&s=' + escape(season_number),

				

                success: function(msg){

					//alert('asdfasdf');

                    $j(episode_block).html(msg);

					

                    }

            });

        }

    }

    function open_track(link_name, season_number, episode_number, keep_visible)

    {

        var link_block = '#episode_' + link_name + '_' + season_number + '_' + episode_number;

        var point_block = '#arrow_' + link_name + '_' + season_number + '_' + episode_number;

        if ($j(link_block + ":visible").length==1 && keep_visible == false)

        {

            $j(link_block).hide();

            $j(point_block).html('<img border="0" src="/images/right.png" alt=""/>');

        }

        else

        {

            $j(link_block).show();

            $j(point_block).html('<img border="0" src="/images/down.png" alt=""/>');

            $j(link_block).html('<img src="/images/loader.gif" alt=""/>');

            $j.ajax({ type: "POST",

                url: 'http://' + tube_hostname + '/actions/link_list_apis.php',

                data: 'l=' + escape(link_name) + '&s=' + escape(season_number) + '&e=' + escape(episode_number),

                success: function(msg){ $j(link_block).html(msg); }

            });

        }

    }

	

    function open_episode_ajax(episode_id)
    {
        var link_block = "#episode_" + episode_id;

//        var point_block = '#arrow_' + link_name + '_' + season_number + '_' + track_id;
        var point_block = "#arrow_" + episode_id;
        if ($j(link_block + ":visible").length==1 ){
            $j(link_block).hide();
            $j(point_block).html('<img border="0" src="/images/right.png" alt=""/>');
        }else{
            $j(link_block).show();
            $j(link_block).html('<img src="/images/loader.gif" alt=""/>');

            $j.ajax({ type: "POST",

                url: 'http://' + tube_hostname + '/ajax/episode/open/' + episode_id,

                data: '',

                success: function(msg){ $j(link_block).html(msg); }

            });

        }

    }

    function open_track_ajax(track_id)

    {

//        var link_block = '#episode_' + link_name + '_' + season_number + '_' + track_id;
        var link_block = "#track_" + track_id;

//        var point_block = '#arrow_' + link_name + '_' + season_number + '_' + track_id;
        var point_block = "#arrow_" + track_id;

        if ($j(link_block + ":visible").length==1 )

        {

            $j(link_block).hide();

            $j(point_block).html('<img border="0" src="/images/right.png" alt=""/>');

        }

        else

        {
            $j(link_block).show();

//            $j(point_block).html('<img border="0" src="/images/down.png" alt=""/>');
//alert('t:'+track_id);return false;

            $j(link_block).html('<img src="/images/loader.gif" alt=""/>');

            $j.ajax({ type: "POST",

                url: 'http://' + tube_hostname + '/ajax/track/open/' + track_id,

                data: '',

                success: function(msg){ $j(link_block).html(msg); }

            });

        }

    }

	


function callback_add_musicto_favorites(request){

	if (request.responseText == 'login'){

		ModalDialog_Show('error_and_link', 441); 

        load_error_form('You have to be logged-in to save your favorites.');
		$j("img.fav_button_loader").hide();
//		$j('#form_error_and_link').html('You have to be logged-in to save your favorites.');

		return false;

	}else{

		var res_split = request.responseText.split('|');

		var result = res_split[0];		

		if (result == 'add') {

			var _fav_id = res_split[1];

			$j('span.fav_button').html('<a  href="javascript:remove_musicfrom_favorites(' + _fav_id + ');">remove from fav</a>');

		//Effect.Fade('select_favorites', { duration: 6.0 });

			return true;

		}

	}

	return false;

}



function add_musicto_favorites(username, userid, js_show_name , js_link_name, js_custom_link, current_season_number, current_episode_number, link_id, click_location){



	$j.ajax({ type: "GET",

		url: 'http://' + tube_hostname + '/actions/store_music_favorites.php',

		data: 'username=' + escape(username) + '&userid=' + escape(userid) + '&js_show_name=' + escape(js_show_name)

			+ '&js_link_name=' + escape(js_link_name) + '&js_custom_link=' + escape(js_custom_link) + '&current_season_number=' + escape(current_season_number)

			+ '&current_episode_number=' + escape(current_episode_number) + '&link_id=' + escape(link_id) + '&click_location=' + escape(click_location),

		complete: callback_add_musicto_favorites

	});

}



function remove_musicfrom_favorites(fav_id){

	$j.ajax( {

        type : "GET"

        , url : 'http://' + tube_hostname + '/actions/remove_music_favorites.php'

        , data : 'fid=' + fav_id

        , complete : callback_remove_musicfrom_favorites

    }

    );

	return void(0);



}



function load_error_form(msg)
{
  $j('#form_error_and_link').html("<br><center>" + msg + "</center><br>");
}


function callback_remove_musicfrom_favorites(request){

	if (request.responseText == 'login') {

        ModalDialog_Show('error_and_link', 441);

        load_error_form('You have to be logged-in to save your favorites.');
		$j("img.fav_button_loader").hide();
        return false;

	}else{

		if(request.responseText == 'removed'){

			$j('span.fav_button').html("<a  href=\"javascript:add_musicto_favorites('" + globals.user_name + "', '" + globals.user_id + "', '" + globals.media_topic + "' , '" + globals.media_js_link + "', '', 0, 0, 0, 1);\"><img src=\"/images/add-favorite-button.gif\" alt=\"Add Favorite\" border=\"0\" /></a>");

			return false;

		}

	}

}





$j(document).ready(function(){

	$j("input.fav_button").bind("click",on_favbutton_click);

});







function on_favbutton_click(event){

		if($j("input.fav_button").attr("disabled")=="disabled"){

			return false;

		}

		var _name = $j(this).attr("name");

		var _spl = _name.split("_");

		var _type = _spl[1];

		var _action = $j(this).val();

		switch(_action){

			case "add":

				var _url = 'http://' + tube_hostname + '/actions/store_' + _type + '_favorites.php';

				var _data = 'username=' + escape(globals.user_name) + '&userid=' + escape(globals.user_id) + '&js_show_name=' + escape(globals.media_js_link) + '&js_link_name=' + escape(globals.media_js_link) + '&js_custom_link=' + escape(globals.custom_js_link);

			break;

			case "del":

				var _url = 'http://' + tube_hostname + '/actions/remove_' + _type + '_favorites.php';

				var _data = 'username=' + escape(globals.user_name) + '&userid=' + escape(globals.user_id) + '&js_show_name=' + escape(globals.media_js_link) + '&js_link_name=' + escape(globals.media_js_link) + '&js_custom_link=' + escape(globals.custom_js_link);

			break;

		}

		$j("input.fav_button").attr("disabled","disabled");

		$j("img.fav_button_loader").show();

		var _ajax_settings = { 'type': "GET",

			'url': _url,

			'data': _data ,

			'complete': callback_on_favbutton_click

		};

//		alert(_ajax_settings.toSource());

		$j.ajax(_ajax_settings);

	}



function callback_on_favbutton_click(resp){

//	alert(resp.responseText);

	if(resp.responseText=='login'){
        ModalDialog_Show('error_and_link', 441);
        load_error_form('You have to be logged-in to save your favorites.');
		$j("img.fav_button_loader").hide();
        return false;
	}else{

		$j("input.fav_button").each(function(){

			if($j(this).val()=='add'){

				$j(this).val('del')

			}else{

				$j(this).val('add');

			}

			$j(this).attr("src","/images/" + $j(this).val() + "-favorite-button.gif");

			$j("img.fav_button_loader").hide();

			$j(this).attr("disabled","");

		});

		return false;

	}

}

function open_episode(link_name, season_number, episode_number, keep_visible) {
    var link_block = '#episode_' + link_name.replace(/\./g,'-') + '_' + season_number + '_' + episode_number;
    var point_block = '#arrow_' + link_name.replace(/\./g,'-') + '_' + season_number + '_' + episode_number;
    var link_class = '#link_episode_'+ link_name.replace(/\./g,'-') + '_' + season_number + '_' + episode_number;
	var add_code_episode = '#episode_add_code_'+ season_number + '_' + episode_number;
	var que_episode = '#queue_show_'+ season_number + '_' + episode_number;
	var like_episode = '#like_show_'+ season_number + '_' + episode_number;
	var watch_episode = '#watch_show_'+ season_number + '_' + episode_number;
	var share_episode = '#share_show_'+ season_number + '_' + episode_number;
	var twit_episode = '#twit_show_'+ season_number + '_' + episode_number;
	var add_data_check = parseInt($j("#add_data").val());
	if ($j(link_block + ":visible").length == 1) {
        $j(link_block).hide();
        $j(point_block).html('<img border="0" src="/images/right.png" alt="right" />');
    } else {
        if((keep_visible == true && $j(link_block).html() == '' && add_data_check == 0) || (keep_visible == true && add_data_check == 1)){
			$j(link_block).html('<img src=/images/loader.gif>');
			$j.ajax( {
				type : "POST"
				, url : '/actions/link_list_links.php'
				, data : 'l=' + escape(link_name) + '&s=' + escape(season_number) + '&e=' + escape(episode_number) + '&user_name=' + globals.user_name
				, success : function (msg) {
					$j(link_block).html(msg);
				}
				
			});
		}
		$j(point_block).html('<img border="0" src="/images/down.png" alt="down" />');
		$j(link_block).show();
        
		if(add_data_check == 0){
			$j.ajax( {
				type : "POST"
				, url : '/actions/episode_like_que.php'
				, data : 'link_name=' + escape(link_name) + '&season_number=' + escape(season_number) + '&episode_number=' + escape(episode_number)
				, success : function (msg) {
					
					var like_que = msg.split("||###||");
					$j(like_episode).html(like_que[0]);
					$j(que_episode).html(like_que[1]);
					$j(watch_episode).html(like_que[2]);					
					$j(share_episode).html(like_que[3]);					
					$j(twit_episode).html('<a href="#" onclick="return twit_click()" target="_blank" class="twitshare" rel="nofollow">Twitter</a>');					
				}
				
			});
			//To Enable google ads uncomment this and comment above one which was for xml ads 
						ad_no = parseInt($j("#ad_counter").val());
						$j.ajax( {
								type : "POST"
								, url : '/actions/episode_google_ads.php'
								, data : 'link_name=' + escape(link_name) + '&season_number=' + escape(season_number) + '&episode_number=' + escape(episode_number) + '&skip_number=' + escape(ad_no) 
								, success : function (msg) {
									if( msg != '' ){
										$j(add_code_episode).html(msg);
										$j(add_code_episode).css('display','block');
										ad_no = ad_no + 1;
										$j("#ad_counter").val(ad_no);
									}
								}
								
							});
			
			/*$j.ajax( {
				type : "POST"
				, url : '/actions/episode_text_ads.php'
				, data : 'link_name=' + escape(link_name) + '&season_number=' + escape(season_number) + '&episode_number=' + escape(episode_number)
				, success : function (msg) {
					if(msg != '1' && msg != ''){
						$j(add_code_episode).html(msg);
						$j(add_code_episode).css('display','block');
					}else if(msg == '1'){
						//For XML Ads
						$j.ajax( {
								type : "POST"
								, url : '/actions/episode_xml_ads.php'
								, data : 'link_name=' + escape(link_name) + '&season_number=' + escape(season_number) + '&episode_number=' + escape(episode_number)
								, success : function (msg) {
									if( msg != '' ){
										$j(add_code_episode).html(msg);
										$j(add_code_episode).css('display','block');
									}
								}
								
							});	
						
						//To Enable google ads uncomment this and comment above one which was for xml ads 
						ad_no = parseInt($j("#ad_counter").val());
						$j.ajax( {
								type : "POST"
								, url : '/actions/episode_google_ads.php'
								, data : 'link_name=' + escape(link_name) + '&season_number=' + escape(season_number) + '&episode_number=' + escape(episode_number) + '&skip_number=' + escape(ad_no) 
								, success : function (msg) {
									if( msg != '' ){
										$j(add_code_episode).html(msg);
										$j(add_code_episode).css('display','block');
										ad_no = ad_no + 1;
										$j("#ad_counter").val(ad_no);
									}
								}
								
							});
					}
				}
				
			});*/
		}
		$j.ajax( {
            type : "POST"
            , url : '/actions/location_click_add_episode.php'
            , data : 'link_name=' + escape(link_name) + '&season_number=' + escape(season_number) + '&episode_number=' + escape(episode_number) +'&user_id=' + globals.user_id
            , success : function (msg) {
                
            }
            
        });
    }
	$j(link_class).toggleClass('selected');
}
function get_ajax_content_description(page,key,field,value,page_number){
	$j.ajax( {
			type : "POST"
			, url : '/get_ajax_content.php'
			, data : 'page='+page+'&field='+field+'&key='+key+'&value='+value+'&page_number='+page_number
			, success : function (contents) {
				var main_html = $j('#'+field+'_'+value).html();
				$j('#'+field+'_'+value).html(main_html+contents);
			}			
	});	
}
function get_google_ads_content_linkspage(link_name,season,episode,type,div_id){
	$j.ajax( {
			type : "POST"
			, url : '/actions/episode_google_ads.php'
			, data : 'link_name='+link_name+'&season='+season+'&episode='+episode+'&type='+type
			, success : function (contents) {
				$j('#'+div_id).html(contents);
				$j('#'+div_id).css('display','block');
			}			
	});	
}
function get_ajax_content_news_display(page,key,field,value,page_number){
	var do_ajax = 0;
	if( value == 'netflix_ad' && page == 'movie_topic'){
		var myRegExp1 = /_admedia_|_adon|_jema|_1001/;
		if(!globals.header_all_utm_params)
			globals.header_all_utm_params = '';
		var utm_check_string = globals.header_all_utm_params.toLowerCase();
		if(utm_check_string.search(myRegExp1) != -1){
			do_ajax = 1;
		}
	}
	if(do_ajax == 0){
		$j.ajax( {
				type : "POST"
				, url : '/get_ajax_content.php'
				, data : 'page='+page+'&field='+field+'&key='+key+'&value='+value+'&page_number='+page_number
				, success : function (contents) {
					$j('#'+field).html(contents);
					$j('#'+field).css('display','block');
				}			
		});	
	}
}
function get_ajax_content_news(page,key,field,value,page_number){
	$j.ajax( {
			type : "POST"
			, url : '/get_ajax_content.php'
			, data : 'page='+page+'&field='+field+'&key='+key+'&value='+value+'&page_number='+page_number
			, success : function (contents) {
				$j('#'+field).html(contents);
			}			
	});	
}
function get_ajax_action_buttons_content(link_name,seasonno,episodeno){
	$j.ajax( {
			type : "POST"
			, url : '/action_buttons_ajax.php'
			, data : 'link_name='+link_name+'&seasonno='+seasonno+'&episodeno='+episodeno
			, success : function (contents) {
				$j('#action-button-overlay').html(contents);
			}			
	});	
}
function get_ads_content(link_name,season_number,episode_number,type, all_utm_params){
	var add_code_episode_netflix = '#episode_add_netflix_'+ season_number + '_' + episode_number;
	var utm_param = 0;
	if(all_utm_params != ""){
		add_code_episode_netflix = add_code_episode_netflix + '_utm';
		utm_param = 1;
	}
	$j.ajax( {
				type : "POST"
				, url : '/actions/episode_ads_netflix.php'
				, data : 'link_name=' + escape(link_name) + '&season_number=' + escape(season_number) + '&episode_number=' + escape(episode_number) + '&type=' + type + '&utm_param=' + utm_param
				, success : function (msg) {
					if(msg != ''){
						$j(add_code_episode_netflix).html(msg);
						$j(add_code_episode_netflix).css('display','block');
					}
				}				
		});	
}
/* end file tvmusics.js */

/* Autocomplete Code in Header*/

/* Simple AJAX Code-Kit (SACK) v1.6.1 */
/* ©2005 Gregory Wild-Smith */
/* www.twilightuniverse.com */
/* Software licenced under a modified X11 licence,
   see documentation or authors website for more details */

function sack(file) {
	this.xmlhttp = null;

	this.resetData = function() {
		this.method = "POST";
  		this.queryStringSeparator = "?";
		this.argumentSeparator = "&";
		this.URLString = "";
		this.encodeURIString = true;
  		this.execute = false;
  		this.element = null;
		this.elementObj = null;
		this.requestFile = file;
		this.vars = new Object();
		this.responseStatus = new Array(2);
  	};

	this.resetFunctions = function() {
  		this.onLoading = function() { };
  		this.onLoaded = function() { };
  		this.onInteractive = function() { };
  		this.onCompletion = function() { };
  		this.onError = function() { };
		this.onFail = function() { };
	};

	this.reset = function() {
		this.resetFunctions();
		this.resetData();
	};

	this.createAJAX = function() {
		try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				this.xmlhttp = null;
			}
		}

		if (! this.xmlhttp) {
			if (typeof XMLHttpRequest != "undefined") {
				this.xmlhttp = new XMLHttpRequest();
			} else {
				this.failed = true;
			}
		}
	};

	this.setVar = function(name, value){
		this.vars[name] = Array(value, false);
	};

	this.encVar = function(name, value, returnvars) {
		if (true == returnvars) {
			return Array(encodeURIComponent(name), encodeURIComponent(value));
		} else {
			this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
		}
	}

	this.processURLString = function(string, encode) {
		encoded = encodeURIComponent(this.argumentSeparator);
		regexp = new RegExp(this.argumentSeparator + "|" + encoded);
		varArray = string.split(regexp);
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split("=");
			if (true == encode){
				this.encVar(urlVars[0], urlVars[1]);
			} else {
				this.setVar(urlVars[0], urlVars[1]);
			}
		}
	}

	this.createURLString = function(urlstring) {
		if (this.encodeURIString && this.URLString.length) {
			this.processURLString(this.URLString, true);
		}

		if (urlstring) {
			if (this.URLString.length) {
				this.URLString += this.argumentSeparator + urlstring;
			} else {
				this.URLString = urlstring;
			}
		}

		// prevents caching of URLString
		this.setVar("rndval", new Date().getTime());

		urlstringtemp = new Array();
		for (key in this.vars) {
			if (false == this.vars[key][1] && true == this.encodeURIString) {
				encoded = this.encVar(key, this.vars[key][0], true);
				delete this.vars[key];
				this.vars[encoded[0]] = Array(encoded[1], true);
				key = encoded[0];
			}

			urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
		}
		if (urlstring){
			this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
		} else {
			this.URLString += urlstringtemp.join(this.argumentSeparator);
		}
	}

	this.runResponse = function() {
		eval(this.response);
	}

	this.runAJAX = function(urlstring) {
		if (this.failed) {
			this.onFail();
		} else {
			this.createURLString(urlstring);
			if (this.element) {
				this.elementObj = document.getElementById(this.element);
			}
			if (this.xmlhttp) {
				var self = this;
				if (this.method == "GET") {
					totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
					this.xmlhttp.open(this.method, this.requestFile, true);
					try {
						this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
					} catch (e) { }
				}

				this.xmlhttp.onreadystatechange = function() {
					switch (self.xmlhttp.readyState) {
						case 1:
							self.onLoading();
							break;
						case 2:
							self.onLoaded();
							break;

						case 3:
							self.onInteractive();
							break;
						case 4:
							self.response = self.xmlhttp.responseText;
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;

							if (self.execute) {
								self.runResponse();
							}

							if (self.elementObj) {
								elemNodeName = self.elementObj.nodeName;
								elemNodeName.toLowerCase();
								if (elemNodeName == "input"
								|| elemNodeName == "select"
								|| elemNodeName == "option"
								|| elemNodeName == "textarea") {
									self.elementObj.value = self.response;
								} else {
									self.elementObj.innerHTML = self.response;
								}
							}
							if (self.responseStatus[0] == "200") {
								self.onCompletion();
							} else {
								self.onError();
							}

							self.URLString = "";
							break;
					}
				};

				this.xmlhttp.send(this.URLString);
			}
		}
	};

	this.reset();
	this.createAJAX();
}


/************************************************************************************************************
	(C) www.dhtmlgoodies.com, April 2006
	
	This is a script from www.dhtmlgoodies.com. You will find this and a lot of other scripts at our website.	
	
	Terms of use:
	You are free to use this script as long as the copyright message is kept intact. However, you may not
	redistribute, sell or repost it without our permission.
	
	Thank you!
	
	www.dhtmlgoodies.com
	Alf Magne Kalleland
	
	************************************************************************************************************/	

	var ajaxBox_offsetX = 0;
	var ajaxBox_offsetY = 0;
	var ajax_list_externalFile = '/showrec.php';	// Path to external file
	var minimumLettersBeforeLookup = 1;	// Number of letters entered before a lookup is performed.
	
	var ajax_list_objects = new Array();
	var ajax_list_cachedLists = new Array();
	var ajax_list_activeInput = true;
	var ajax_list_activeItem;
	var ajax_list_optionDivFirstItem = false;
	var ajax_list_currentLetters = new Array();
	var ajax_optionDiv = false;
	var ajax_optionDiv_iframe = false;

	var ajax_list_MSIE = false;
	if(navigator.userAgent.indexOf('MSIE')>=0 && navigator.userAgent.indexOf('Opera')<0)ajax_list_MSIE=true;
	
	var currentListIndex = 0;
	
	function ajax_getTopPos(inputObj)
	{
		
	  var returnValue = inputObj.offsetTop;
	  while((inputObj = inputObj.offsetParent) != null){
	  	returnValue += inputObj.offsetTop;
	  }
	  return returnValue;
	}
	function ajax_list_cancelEvent()
	{
		return false;
	}
	
	function ajax_getLeftPos(inputObj)
	{
	  var returnValue = inputObj.offsetLeft;
	  while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft;
	  
	  return returnValue;
	}
	
	function ajax_option_setValue(e,inputObj)
	{
		if(!inputObj)inputObj=this;
		var tmpValue = inputObj.innerHTML;
		if(ajax_list_MSIE)tmpValue = inputObj.innerText;else tmpValue = inputObj.textContent;
		if(!tmpValue)tmpValue = inputObj.innerHTML;
		if(tmpValue.indexOf("View all search results for")!=-1)
		{
		   var mySplitResult = tmpValue.split('"');	
		   ajax_list_activeInput.value = mySplitResult[1];
		}
		else
		{
		    var string_title = tmpValue;
			var string_link = inputObj.id;
			string_title = string_title.toLowerCase();
			
			var explode_string_ = string_link.lastIndexOf("-");
			if(explode_string_ !=-1)
			{
				var grap_data_ = string_link.substr(explode_string_+1);
				
				var link_split_res_ = string_title.split(grap_data_);
				if(link_split_res_[0].indexOf("(")!=-1)
					ajax_list_activeInput.value = link_split_res_[0]+grap_data_+')';
				else
					ajax_list_activeInput.value = link_split_res_[0]+grap_data_;	
			}
			else
			{
			   if(string_title.lastIndexOf("episodes")!=-1)
			   {
				  var spilt_ = string_link.split('/show/');
				  
				  ajax_list_activeInput.value = spilt_[1];
			   }
			   else
				ajax_list_activeInput.value = string_title;
			
			}
			//ajax_list_activeInput.value = tmpValue;
		}
		//if(document.getElementById(ajax_list_activeInput.name + '_hidden'))document.getElementById(ajax_list_activeInput.name + '_hidden').value = inputObj.id; 
		//alert(inputObj.id);
		
		doSearch_Btn(inputObj.id);
		ajax_options_hide();
	}
	
	function ajax_options_hide()
	{
		if(ajax_optionDiv)ajax_optionDiv.style.display='none';	
		if(ajax_optionDiv_iframe)ajax_optionDiv_iframe.style.display='none';
	}

	function ajax_options_rollOverActiveItem(item,fromKeyBoard)
	{
		
		if(ajax_list_activeItem)ajax_list_activeItem.className='optionDiv';
		item.className='optionDivSelected';
		ajax_list_activeItem = item;
        var selectid = item.id;
		//alert(ajax_list_activeItem.id);
		var textContent = jQuery(".optionDivSelected").html();
        if(textContent.indexOf("View all search results for") != -1)
		{
		   var mySplit_Result = textContent.split('"');
		   document.getElementById(selectid).value = mySplit_Result[1];
		}
		else
		{
			var string = textContent;
			var string2 = ajax_list_activeItem.id;
			string = string.toLowerCase();
			
			var explode_string = string2.lastIndexOf("-");
			if(explode_string !=-1)
			{
				var grap_data = string2.substr(explode_string+1);
				
				var link_split_res = string.split(grap_data);
				if(link_split_res[0].indexOf("(")!=-1)
					document.getElementById(selectid).value = link_split_res[0]+grap_data+')';
				else
					document.getElementById(selectid).value = link_split_res[0]+grap_data;
			}
			else
			{
			  if(string.lastIndexOf("episodes")!=-1)
			   {
				  var spilt_rs = string2.split('/show/');
				  
				  document.getElementById(selectid).value = spilt_rs[1];
			   }
			  else 
			  document.getElementById(selectid).value = string;    
			}
		}
	 	
	  /*
		if(ajax_list_activeItem.id.indexOf("View all search results for")!=-1)
		{
		   var mySplit_Result = ajax_list_activeItem.id.split('"');
		   document.getElementById(selectid).value = mySplit_Result[1];
		}
		else
		{
			var string = ajax_list_activeItem.id;
			var string2 = ajax_list_activeItem.id;
			string = string.toLowerCase();
			
			var explode_string = string2.lastIndexOf("-");
			if(explode_string !=-1)
			{
				var grap_data = string2.substr(explode_string+1);
				
				var link_split_res = string.split(grap_data);
				if(link_split_res[0].indexOf("(")!=-1)
					document.getElementById(selectid).value = link_split_res[0]+grap_data+')';
				else
					document.getElementById(selectid).value = link_split_res[0]+grap_data;
			}
			else
			{
			  if(string.lastIndexOf("episodes")!=-1)
			   {
				  var spilt_rs = string2.split('/show/');
				  
				  document.getElementById(selectid).value = spilt_rs[1];
			   }
			  else 
			  document.getElementById(selectid).value = string;    
			}
		}*/
		
		if(fromKeyBoard){
			if(ajax_list_activeItem.offsetTop>ajax_optionDiv.offsetHeight){
				ajax_optionDiv.scrollTop = ajax_list_activeItem.offsetTop - ajax_optionDiv.offsetHeight + ajax_list_activeItem.offsetHeight + 2 ;
			}
			if(ajax_list_activeItem.offsetTop<ajax_optionDiv.scrollTop)
			{
				ajax_optionDiv.scrollTop = 0;	
			}
		}
	}
	
	function ajax_option_list_buildList(letters,paramToExternalFile)
	{
		
		ajax_optionDiv.innerHTML = '';
		ajax_list_activeItem = false;
		if(ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()].length<=1){
			ajax_options_hide();
			return;			
		}
		
		
		
		ajax_list_optionDivFirstItem = false;
		var optionsAdded = false;
		for(var no=0;no<ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()].length;no++){
			if(ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()][no].length==0)continue;
			optionsAdded = true;
			var div = document.createElement('DIV');
			var items = ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()][no].split(/###/gi);
			
			if(ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()].length==1 && ajax_list_activeInput.value == items[0]){
				ajax_options_hide();
				return;						
			}
			
			
			div.innerHTML = items[items.length-1];
			div.id = items[0];
			div.className='optionDiv';
			div.onmouseover = function(){ ajax_options_rollOverActiveItem(this,false) }
			div.onclick = ajax_option_setValue;
			if(!ajax_list_optionDivFirstItem)ajax_list_optionDivFirstItem = div;
			ajax_optionDiv.appendChild(div);
		}	
		if(optionsAdded){
			ajax_optionDiv.style.display='block';
			if(ajax_optionDiv_iframe)ajax_optionDiv_iframe.style.display='';
			//ajax_options_rollOverActiveItem(ajax_list_optionDivFirstItem,true);
		}
				
	}
	
	function ajax_option_list_showContent(ajaxIndex,inputObj,paramToExternalFile,whichIndex)
	{
		if(whichIndex!=currentListIndex)return;
		var letters = inputObj.value;
		var content = ajax_list_objects[ajaxIndex].response;
		var elements = content.split('|');
		
		ajax_list_cachedLists[paramToExternalFile][letters.toLowerCase()] = elements;
		ajax_option_list_buildList(letters,paramToExternalFile);
		
	}
	
	function ajax_option_resize(inputObj)
	{
		ajax_optionDiv.style.top = (ajax_getTopPos(inputObj) + inputObj.offsetHeight + ajaxBox_offsetY) + 'px';
		ajax_optionDiv.style.left = (ajax_getLeftPos(inputObj) + ajaxBox_offsetX) + 'px';
		if(ajax_optionDiv_iframe){
			ajax_optionDiv_iframe.style.left = ajax_optionDiv.style.left;
			ajax_optionDiv_iframe.style.top = ajax_optionDiv.style.top;			
		}		
		
	}
	
	function ajax_showOptions(inputObj,paramToExternalFile,e)
	{
		var last_str = '';
		if(e.keyCode==13 || e.keyCode==9)return;
		if(ajax_list_currentLetters[inputObj.name]==inputObj.value)return;
		if(!ajax_list_cachedLists[paramToExternalFile])ajax_list_cachedLists[paramToExternalFile] = new Array();
		ajax_list_currentLetters[inputObj.name] = inputObj.value;
		if(!ajax_optionDiv){
			ajax_optionDiv = document.createElement('DIV');
			ajax_optionDiv.id = 'ajax_listOfOptions';	
			document.body.appendChild(ajax_optionDiv);
			
			if(ajax_list_MSIE){
				ajax_optionDiv_iframe = document.createElement('IFRAME');
				ajax_optionDiv_iframe.border='0';
				ajax_optionDiv_iframe.style.width = ajax_optionDiv.clientWidth + 'px';
				ajax_optionDiv_iframe.style.height = ajax_optionDiv.clientHeight + 'px';
				ajax_optionDiv_iframe.id = 'ajax_listOfOptions_iframe';
				
				document.body.appendChild(ajax_optionDiv_iframe);
			}
			
			var allInputs = document.getElementsByTagName('INPUT');
			for(var no=0;no<allInputs.length;no++){
				if(!allInputs[no].onkeyup)allInputs[no].onfocus = ajax_options_hide;
			}			
			var allSelects = document.getElementsByTagName('SELECT');
			for(var no=0;no<allSelects.length;no++){
				allSelects[no].onfocus = ajax_options_hide;
			}

			var oldonkeydown=document.body.onkeydown;
			if(typeof oldonkeydown!='function'){
				document.body.onkeydown=ajax_option_keyNavigation;
			}else{
				document.body.onkeydown=function(){
					oldonkeydown();
				ajax_option_keyNavigation() ;}
			}
			var oldonresize=document.body.onresize;
			if(typeof oldonresize!='function'){
				document.body.onresize=function() {ajax_option_resize(inputObj); };
			}else{
				document.body.onresize=function(){oldonresize();
				ajax_option_resize(inputObj) ;}
			}
				
		}
		
		if(inputObj.value.length<minimumLettersBeforeLookup){
			ajax_options_hide();
			return;
		}
				

		ajax_optionDiv.style.top = (ajax_getTopPos(inputObj) + inputObj.offsetHeight + ajaxBox_offsetY) + 'px';
		ajax_optionDiv.style.left = (ajax_getLeftPos(inputObj) + ajaxBox_offsetX) + 'px';
		if(ajax_optionDiv_iframe){
			ajax_optionDiv_iframe.style.left = ajax_optionDiv.style.left;
			ajax_optionDiv_iframe.style.top = ajax_optionDiv.style.top;			
		}
		
		ajax_list_activeInput = inputObj;
		ajax_optionDiv.onselectstart =  ajax_list_cancelEvent;
		currentListIndex++;
		if(ajax_list_cachedLists[paramToExternalFile][inputObj.value.toLowerCase()]){
			ajax_option_list_buildList(inputObj.value,paramToExternalFile,currentListIndex);			
		}else{
			if(e.keyCode!=40 && e.keyCode!=38){
				var tmpIndex=currentListIndex/1;
				ajax_optionDiv.innerHTML = '';
				var ajaxIndex = ajax_list_objects.length;
				ajax_list_objects[ajaxIndex] = new sack();
				var source1 = '';
				last_str = '';
				last_str = replace_space(inputObj.value);
				//alert('last str : '+last_str);
				var url = ajax_list_externalFile + '?' + paramToExternalFile + '=1&letters=' + last_str;
				ajax_list_objects[ajaxIndex].requestFile = url;	// Specifying which file to get
				ajax_list_objects[ajaxIndex].onCompletion = function(){ ajax_option_list_showContent(ajaxIndex,inputObj,paramToExternalFile,tmpIndex); };	// Specify function that will be executed after file has been found
				ajax_list_objects[ajaxIndex].runAJAX();		// Execute AJAX function
		   }
		}
		
			
	}
	function replace_space(source)
	{
		var is_exits = source.search(' ');
		var is_exits_and = source.search('&');
		var is_question_m = new RegExp("([?])");
		if(is_exits > 0 || is_exits_and > 0 || source.match(is_question_m))
		{
			source1 = source.replace('&','-01-');
			source1 = source1.replace(' ','+');
			source1 = source1.replace('?','--010--');
			replace_space(source1);	
		}
		else
		{
			source1 = source;	
		}
		return source1;
	}
	function ajax_option_keyNavigation(e)
	{
		if(document.all)e = event;
		if(!ajax_optionDiv)return;
		if(ajax_optionDiv.style.display=='none')return;
		
		if(e.keyCode==38){	// Up arrow
			if(!ajax_list_activeItem)return;
			if(ajax_list_activeItem && !ajax_list_activeItem.previousSibling)return;
			ajax_options_rollOverActiveItem(ajax_list_activeItem.previousSibling,true);
		}
		
		if(e.keyCode==40){	// Down arrow
			if(!ajax_list_activeItem){
				ajax_options_rollOverActiveItem(ajax_list_optionDivFirstItem,true);
			   return true;
			}else{
				if(!ajax_list_activeItem.nextSibling)return;
				ajax_options_rollOverActiveItem(ajax_list_activeItem.nextSibling,true);
			return true;
			}
			
		 return true;	
		}
		
		if(e.keyCode==13 || e.keyCode==9){	// Enter key or tab key
			if(ajax_list_activeItem && ajax_list_activeItem.className=='optionDivSelected')ajax_option_setValue(false,ajax_list_activeItem);
			if(e.keyCode==13)return false; else return true;
		}
		if(e.keyCode==27){	// Escape key
			ajax_options_hide();			
		}
	}
	
	
	document.documentElement.onclick = autoHideList;
	
	function autoHideList(e)
	{
		if(document.all)e = event;
		
		if (e.target) source = e.target;
			else if (e.srcElement) source = e.srcElement;
			if (source.nodeType == 3) // defeat Safari bug
				source = source.parentNode;		
		if(source.tagName.toLowerCase()!='input' && source.tagName.toLowerCase()!='textarea')ajax_options_hide();
		
	}
/* End of Autocomplete Code*/



/* class_base.js file code*/

/*
*  Ajax Autocomplete for jQuery, version 1.1
*  (c) 2009 Tomas Kirda
*
*  Ajax Autocomplete for jQuery is freely distributable under the terms of an MIT-style license.
*  For details, see the web site: http://www.devbridge.com/projects/autocomplete/jquery/
*
*  Last Review: 09/27/2009
*/

/*jslint onevar: true, evil: true, nomen: true, eqeqeq: true, bitwise: true, regexp: true, newcap: true, immed: true */
/*global window: true, document: true, clearInterval: true, setInterval: true, jQuery: true */

(function($) {

  var reEscape = new RegExp('(\\' + ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'].join('|\\') + ')', 'g');

  function fnFormatResult(value, data, currentValue) {
    var pattern = '(' + currentValue.replace(reEscape, '\\$1') + ')';
    return value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>');
  }

  function Autocomplete(el, options) {
    this.el = $(el);
    this.el.attr('autocomplete', 'off');
    this.suggestions = [];
    this.data = [];
    this.badQueries = [];
    this.selectedIndex = -1;
    this.currentValue = this.el.val();
    this.intervalId = 0;
    this.cachedResponse = [];
    this.onChangeInterval = null;
    this.ignoreValueChange = false;
    this.serviceUrl = options.serviceUrl;
    this.isLocal = false;
    this.options = {
      autoSubmit: false,
      minChars: 1,
      maxHeight: 300,
      deferRequestBy: 0,
      width: 0,
      highlight: true,
      params: {},
      fnFormatResult: fnFormatResult,
      delimiter: null,
      zIndex: 9999
    };
    this.initialize();
    this.setOptions(options);
  }
  
  $.fn.autocomplete = function(options) {
    return new Autocomplete(this.get(0), options);
  };


  Autocomplete.prototype = {

    killerFn: null,

    initialize: function() {

      var me, uid, autocompleteElId;
      me = this;
      uid = new Date().getTime();
      autocompleteElId = 'Autocomplete_' + uid;

      this.killerFn = function(e) {
        if ($(e.target).parents('.autocomplete').size() === 0) {
          me.killSuggestions();
          me.disableKillerFn();
        }
      };

      if (!this.options.width) { this.options.width = this.el.width(); }
      this.mainContainerId = 'AutocompleteContainter_' + uid;

      $('<div id="' + this.mainContainerId + '" style="position:absolute;z-index:9999;"><div class="autocomplete-w1"><div class="autocomplete" id="' + autocompleteElId + '" style="display:none; width:300px;"></div></div></div>').appendTo('body');

      this.container = $('#' + autocompleteElId);
      this.fixPosition();
      if (window.opera) {
        this.el.keypress(function(e) { me.onKeyPress(e); });
      } else {
        this.el.keydown(function(e) { me.onKeyPress(e); });
      }
      this.el.keyup(function(e) { me.onKeyUp(e); });
      this.el.blur(function() { me.enableKillerFn(); });
      this.el.focus(function() { me.fixPosition(); });
    },
    
    setOptions: function(options){
      var o = this.options;
      $.extend(o, options);
      if(o.lookup){
        this.isLocal = true;
        if($.isArray(o.lookup)){ o.lookup = { suggestions:o.lookup, data:[] }; }
      }
      $('#'+this.mainContainerId).css({ zIndex:o.zIndex });
      this.container.css({ maxHeight: o.maxHeight + 'px', width:o.width });
    },
    
    clearCache: function(){
      this.cachedResponse = [];
      this.badQueries = [];
    },
    
    disable: function(){
      this.disabled = true;
    },
    
    enable: function(){
      this.disabled = false;
    },

    fixPosition: function() {
      var offset = this.el.offset();
      $('#' + this.mainContainerId).css({ top: (offset.top + this.el.innerHeight()) + 'px', left: offset.left + 'px' });
    },

    enableKillerFn: function() {
      var me = this;
      $(document).bind('click', me.killerFn);
    },

    disableKillerFn: function() {
      var me = this;
      $(document).unbind('click', me.killerFn);
    },

    killSuggestions: function() {
      var me = this;
      this.stopKillSuggestions();
      this.intervalId = window.setInterval(function() { me.hide(); me.stopKillSuggestions(); }, 300);
    },

    stopKillSuggestions: function() {
      window.clearInterval(this.intervalId);
    },

    onKeyPress: function(e) {
      if (this.disabled || !this.enabled) { return; }
      // return will exit the function
      // and event will not be prevented
      switch (e.keyCode) {
        case 27: //KEY_ESC:
          this.el.val(this.currentValue);
          this.hide();
          break;
        case 9: //KEY_TAB:
        case 13: //KEY_RETURN:
          if (this.selectedIndex === -1) {
            this.hide();
            return;
          }
          this.select(this.selectedIndex);
          if (e.keyCode === 9/* KEY_TAB */) { return; }
          break;
        case 38: //KEY_UP:
          this.moveUp();
          break;
        case 40: //KEY_DOWN:
          this.moveDown();
          break;
        default:
          return;
      }
      e.stopImmediatePropagation();
      e.preventDefault();
    },

    onKeyUp: function(e) {
      if(this.disabled){ return; }
      switch (e.keyCode) {
        case 38: //KEY_UP:
        case 40: //KEY_DOWN:
          return;
      }
      clearInterval(this.onChangeInterval);
      if (this.currentValue !== this.el.val()) {
        if (this.options.deferRequestBy > 0) {
          // Defer lookup in case when value changes very quickly:
          var me = this;
          this.onChangeInterval = setInterval(function() { me.onValueChange(); }, this.options.deferRequestBy);
        } else {
          this.onValueChange();
        }
      }
    },

    onValueChange: function() {
      clearInterval(this.onChangeInterval);
      this.currentValue = this.el.val();
      var q = this.getQuery(this.currentValue);
      this.selectedIndex = -1;
      if (this.ignoreValueChange) {
        this.ignoreValueChange = false;
        return;
      }
      if (q === '' || q.length < this.options.minChars) {
        this.hide();
      } else {
        this.getSuggestions(q);
      }
    },

    getQuery: function(val) {
      var d, arr;
      d = this.options.delimiter;
      if (!d) { return $.trim(val); }
      arr = val.split(d);
      return $.trim(arr[arr.length - 1]);
    },

    getSuggestionsLocal: function(q) {
      var ret, arr, len, val, i;
      arr = this.options.lookup;
      len = arr.suggestions.length;
      ret = { suggestions:[], data:[] };
      q = q.toLowerCase();
      for(i=0; i< len; i++){
        val = arr.suggestions[i];
        if(val.toLowerCase().indexOf(q) === 0){
          ret.suggestions.push(val);
          ret.data.push(arr.data[i]);
        }
      }
      return ret;
    },
    
    getSuggestions: function(q) {
      var cr, me;
      cr = this.isLocal ? this.getSuggestionsLocal(q) : this.cachedResponse[q];
      if (cr && $.isArray(cr.suggestions)) {
        this.suggestions = cr.suggestions;
        this.data = cr.data;
        this.suggest();
      } else if (!this.isBadQuery(q)) {
        me = this;
        me.options.params.query = q;
        $.get(this.serviceUrl, me.options.params, function(txt) { me.processResponse(txt); }, 'text');
      }
    },

    isBadQuery: function(q) {
      var i = this.badQueries.length;
      while (i--) {
        if (q.indexOf(this.badQueries[i]) === 0) { return true; }
      }
      return false;
    },

    hide: function() {
      this.enabled = false;
      this.selectedIndex = -1;
      this.container.hide();
    },

    suggest: function() {
      if (this.suggestions.length === 0) {
        this.hide();
        return;
      }

      var me, len, div, f, v, i, s, mOver, mClick;
      me = this;
      len = this.suggestions.length;
      f = this.options.fnFormatResult;
      v = this.getQuery(this.currentValue);
      mOver = function(xi) { return function() { me.activate(xi); }; };
      mClick = function(xi) { return function() { me.select(xi); }; };
      this.container.hide().empty();
      for (i = 0; i < len; i++) {
        s = this.suggestions[i];
        div = $((me.selectedIndex === i ? '<div class="selected"' : '<div') + ' title="' + s + '">' + f(s, this.data[i], v) + '</div>');
        div.mouseover(mOver(i));
        div.click(mClick(i));
        this.container.append(div);
      }
      this.enabled = true;
      this.container.show();
    },

    processResponse: function(text) {
      var response;
      try {
        response = eval('(' + text + ')');
      } catch (err) { return; }
      if (!$.isArray(response.data)) { response.data = []; }
      this.cachedResponse[response.query] = response;
      if (response.suggestions.length === 0) { this.badQueries.push(response.query); }
      if (response.query === this.getQuery(this.currentValue)) {
        this.suggestions = response.suggestions;
        this.data = response.data;
        this.suggest(); 
      }
    },

    activate: function(index) {
      var divs, activeItem;
      divs = this.container.children();
      // Clear previous selection:
      if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) {
        $(divs.get(this.selectedIndex)).attr('class', '');
      }
      this.selectedIndex = index;
      if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) {
        activeItem = divs.get(this.selectedIndex);
        $(activeItem).attr('class', 'selected');
      }
      return activeItem;
    },

    deactivate: function(div, index) {
      div.className = '';
      if (this.selectedIndex === index) { this.selectedIndex = -1; }
    },

    select: function(i) {
      var selectedValue, f;
      selectedValue = this.suggestions[i];
      if (selectedValue) {
        this.el.val(selectedValue);
        if (this.options.autoSubmit) {
          f = this.el.parents('form');
          if (f.length > 0) { f.get(0).submit(); }
        }
        this.ignoreValueChange = true;
        this.hide();
        this.onSelect(i);
      }
    },

    moveUp: function() {
      if (this.selectedIndex === -1) { return; }
      if (this.selectedIndex === 0) {
        this.container.children().get(0).className = '';
        this.selectedIndex = -1;
        this.el.val(this.currentValue);
        return;
      }
      this.adjustScroll(this.selectedIndex - 1);
    },

    moveDown: function() {
      if (this.selectedIndex === (this.suggestions.length - 1)) { return; }
      this.adjustScroll(this.selectedIndex + 1);
    },

    adjustScroll: function(i) {
      var activeItem, offsetTop, upperBound, lowerBound;
      activeItem = this.activate(i);
      offsetTop = activeItem.offsetTop;
      upperBound = this.container.scrollTop();
      lowerBound = upperBound + this.options.maxHeight - 25;
      if (offsetTop < upperBound) {
        this.container.scrollTop(offsetTop);
      } else if (offsetTop > lowerBound) {
        this.container.scrollTop(offsetTop - this.options.maxHeight + 25);
      }
      //this.el.val(this.suggestions[i]);
    },

    onSelect: function(i) {
      var me, onSelect, getValue, s, d;
      me = this;
      onSelect = me.options.onSelect;
      getValue = function(value) {
        var del, currVal, arr;
        del = me.options.delimiter;
        if (!del) { return value; }
        currVal = me.currentValue;
        arr = currVal.split(del);
        if (arr.length === 1) { return value; }
        return currVal.substr(0, currVal.length - arr[arr.length - 1].length) + value;
      };
      s = me.suggestions[i];
      d = me.data[i];
      me.el.val(getValue(s));
      if ($.isFunction(onSelect)) { onSelect(s, d); }
    }

  };

}(jQuery));

/*
var SocialEngineAPI = {

  version : '0.1.0alpha'

};



SocialEngineAPI.Base = new Class({

  // Methods
  initialize: function()
  {
    this.version = SocialEngineAPI.version; 
  },
  
  
  
  RegisterModule: function(moduleObject)
  {
    moduleObject.Base = this;
  }

});
*/

/* class_comments.js file */

// Required language variables: 39,155,175,182,183,184,185,187,784,787,829,830,831,832,833,834,835,854,856,891,1025,1026,1032,1034,1071


/*SocialEngineAPI.Comments = new Class({
  
  // Class
	//Implements: [Options],
  
  // Properties
  Base: {},
  
  page: 1,
  
  total: 0,
  
  changed: false,
  
  isEditing: false,
  
  
  options: {
    // Controls ajax request options
    'ajaxURL' : 'misc_js.php',
    'ajaxMethod' : 'post',
    'ajaxSecure' : false,
    
    // Can the viewer comment
    'canComment' : false,
    'commentHTML' : false,
    'commentCode' : false,
    
    // Controls the height of the comment box
    'originalHeight' : 70,
    
    // The type of comment ex. 'media'
    'type' : false,
    
    // The column that identifies the type ex. 'media_id'
    'typeIdentifier' : false,
    
    // The actual ID of the object commented on
    'typeID' : false,

    // Pagination Info
    'paginate' : false,
    'cpp' : false,

    // Comment links
    'commentLinks' : {'reply' : false, 'walltowall' : false},
    
    // Some other stuff to identify the object
    'object_owner' : false,
    'object_owner_id' : false,
    'typeTab' : false,
    'typeCol' : false,
    'typeTabParent' : false,
    'typeColParent' : false,
    'typeChild' : false
  },
  
  
  
  
  // Methods
  initialize: function(options)
  {
    this.setOptions(options);
    
    if( this.options.initialTotal ) this.total = this.options.initialTotal;

    var bind = this;
    window.addEvent('domready', function()
    {
      bind.showPostComment();
      
      bind.options.originalHeight = textarea_autogrow('comment_body');
      bind.getComments(1);
    });
  },
  
  
  
  
  showPostComment: function()
  {
    var innerHTML = "";
    
    // POST COMMENT
    innerHTML += 
      "<div class='comment_headline'>Comments (<span class='tc' id='" + this.options.type + '_' + this.options.typeID + '_totalcomments' + "'>" + this.total + "</span>)" +
      "</div>";
      
    if( this.options.canComment )
    {
      innerHTML += 
        "<form action='misc_js.php' method='post' target='ajaxframe'>" +
          "<div class='profile_postcomment'>" +
            "<textarea name='comment_body' id='comment_body' cols='25' class='comment_area'>Write Something...</textarea>";
      
      if( this.options.commentHTML ) innerHTML += 
            "<div style='margin-top: 5px;'>Allowed HTML Tags:<br></div>";
      
      if( this.options.commentCode ) innerHTML += 
            "<div style='float: left; margin-top: 5px;'>" +
              "<a href='javascript:void(0);' onClick=\"this.blur();$('secure_image').src=$('secure_image').src+'?'+(new Date()).getTime();\">" +
                "<img src='./images/secure.php' id='secure_image' border='0' height='20' width='67' class='signup_code'>" + 
              "</a>" +
              " <input type='text' name='comment_secure' id='comment_secure' class='text' size='6' maxlength='10'> " +
              "<img src='./images/icons/tip.gif' border='0' class='Tips1' style='vertical-align: middle;' title='" + this.Base.Language.Translate(856) + "'>" +
            "</div>";
      
      innerHTML += 
            "<div style='text-align: right; margin-top: 5px;'>" +
            "<input type='submit' id='comment_submit' class='button' value='Post Comment'>" +
            "<input type='hidden' name='task' value='comment_post'>" +
            "<input type='hidden' name='type' value='" + this.options.type + "'>" +
            "<input type='hidden' name='iden' value='" + this.options.typeIdentifier + "'>" +
            "<input type='hidden' name='value' value='" + this.options.typeID + "'>";
      
      if( this.options.object_owner && this.options.object_owner_id )
      {
        innerHTML += '<input type="hidden" name="object_owner" value="' + this.options.object_owner + '">' +
		     '<input type="hidden" name="object_owner_id" value="' + this.options.object_owner_id + '">';
      } else {
        innerHTML += '<input type="hidden" name="user" value="' + this.Base.Owner.user_info.user_username + '">';
      }

      if( this.options.typeTab ) innerHTML += 
            "<input type='hidden' name='tab' value='" + this.options.typeTab + "'>";
      
      if( this.options.typeCol ) innerHTML += 
            "<input type='hidden' name='col' value='" + this.options.typeCol + "'>";
      
      if( this.options.typeTabParent ) innerHTML += 
          '<input type="hidden" name="tab_parent" value="' + this.options.typeTabParent + '">';
      
      if( this.options.typeColParent ) innerHTML += 
          '<input type="hidden" name="col_parent" value="' + this.options.typeColParent + '">';
      
      if( this.options.typeChild ) innerHTML += 
          '<input type="hidden" name="child" value="1">';
      
      innerHTML += 
            "</div>" +
            "<div id='comment_error' style='color: #FF0000; display: none;'></div>" +
          "</div>" +
        "</form>";
    }
    
    // DELETE COMMENT
    innerHTML += 
      '<div style="display: none;" id="confirmcommentdelete">' +
        '<div style="margin-top: 10px;">' +
          this.Base.Language.Translate(1026) +
        '</div>' +
        '<br />' +
        '<form action="misc_js.php" method="post" target="ajaxframe">' +
        '<input type="submit" class="button" value="' + this.Base.Language.Translate(175) + '" onClick="parent.TB_remove();"> ' +
        '<input type="button" class="button" value="' + this.Base.Language.Translate(39) + '" onClick="parent.TB_remove();">' +
        '<input type="hidden" name="task" value="comment_delete">' +
        '<input type="hidden" name="comment_id" id="del_comment_id" value="0">' +
        '<input type="hidden" name="type" value="' + this.options.type + '">' +
        '<input type="hidden" name="iden" value="' + this.options.typeIdentifier + '">' +
        '<input type="hidden" name="value" value="' + this.options.typeID + '">';

    if( this.options.object_owner && this.options.object_owner_id )
    {
      innerHTML += '<input type="hidden" name="object_owner" value="' + this.options.object_owner + '">' +
		   '<input type="hidden" name="object_owner_id" value="' + this.options.object_owner_id + '">';
    } else {
      innerHTML += '<input type="hidden" name="user" value="' + this.Base.Owner.user_info.user_username + '">';
    }

    if( this.options.typeTab ) innerHTML += 
        '<input type="hidden" name="tab" value="' + this.options.typeTab + '">';
    
    if( this.options.typeCol ) innerHTML += 
        '<input type="hidden" name="col" value="' + this.options.typeCol + '">';
    
    if( this.options.typeTabParent ) innerHTML += 
        '<input type="hidden" name="tab_parent" value="' + this.options.typeTabParent + '">';
    
    if( this.options.typeColParent ) innerHTML += 
        '<input type="hidden" name="col_parent" value="' + this.options.typeColParent + '">';
    
    if( this.options.typeChild ) innerHTML += 
        '<input type="hidden" name="child" value="1">';

  
    
    innerHTML += 
        '</form>' +
      '</div>';
    
    
    
    var postCommentContainerElement = $(this.options.type + '_' + this.options.typeID + '_postcomment');
    postCommentContainerElement.innerHTML = innerHTML;
    
    
    // Add events
    var bind = this;
    if( this.options.canComment )
    {
      postCommentContainerElement.getElement('form').addEvent('submit', function()    { bind.checkText();       });
      postCommentContainerElement.getElement('textarea').addEvent('focus', function() { bind.removeText(this);  });
      postCommentContainerElement.getElement('textarea').addEvent('blur', function()  { bind.addText(this);     });
    }
    
  },
  
  
  
  
  getComments: function(direction)
  {
    if( direction=='next' )
      this.page++;
    else if( direction=='previous' )
      this.page--;
    else if( $type(direction) )
      this.page = direction;
    
    if( this.options.paginate ) {

      window.scroll(0,0);
    } else {
      this.options.cpp = this.total;
    }

    if( this.options.object_owner && this.options.object_owner_id )
    {
      var object_owner = this.options.object_owner;
      var object_owner_id = this.options.object_owner_id;
      var user = '';
    } else {
      var object_owner = '';
      var object_owner_id = '';
      var user = this.Base.Owner.user_info.user_username;      
    }

    // AJAX
    var bind = this;
    var request = new Request.JSON({
      'url' : this.options.ajaxURL,
      'method' : this.options.ajaxMethod,
      'secure' : this.options.ajaxSecure,
      'data' : {
        'task'  : 'comment_get',
        'user'  : user,
	'object_owner' : object_owner,
	'object_owner_id' : object_owner_id,
        'type'  : this.options.type,
        'iden'  : this.options.typeIdentifier,
        'value' : this.options.typeID,
        'cpp'   : this.options.cpp,
        'p'     : this.page
      },
      'onComplete' : function(responseObject, responseText)
      {
        bind.updateComments(responseObject);
      }
    });
    
    request.send();
  },
  
  
  
  
  // THIS FUNCTION UPDATES THE COMMENTS
  updateComments: function(responseObject)
  {
    if( $type(responseObject)!="object" )
    {
      alert('There was an error processing the request.');
      return false;
    }
    
    
    // Prepare
    this.total  = parseInt(responseObject.total_comments) || 0;
    this.page   = responseObject.p;
    
    var maxpage = responseObject.maxpage;
    var p_start = responseObject.p_start;
    var p_end   = responseObject.p_end;
    
    var totalCommentElement     = $(this.options.type + '_' + this.options.typeID + '_totalcomments');
    var commentContainerElement = $(this.options.type + '_' + this.options.typeID + '_comments');
    var comments = $H(responseObject.comments);
    
    // UPDATE TOTAL COMMENTS AND PAGE VARS
    totalCommentElement.innerHTML = this.total;

    // CREATE DIV TO HOLD COMMENT BODY FOR CLEANING
    var commentBodyDiv = document.createElement('div');
    
    // EMPTY CONTAINER 
    commentContainerElement.empty();
    
    // LOOP OVER COMMENTS
    var bind = this;
    if(bind.Base.Core.settings.setting_url) { var querySeparator = '?'; } else { var querySeparator = '&'; }
    comments.each(function(commentObject, commentID)
    {
      var newComment = new Element('div', {
        'id' : 'comment_' + commentID
      });
      
      // BUILD COMMENT
      var newCommentInnerHTML = "<div style='margin-top: 10px; margin-bottom: 20px;'>";
      
      // AUTHOR PHOTO
      if( commentObject.comment_authoruser_id && commentObject.comment_authoruser_exists )
        newCommentInnerHTML += "<div style='float: left; text-align: center; width: 90px;'><a href='" + commentObject.comment_authoruser_url + "'><img src='" + commentObject.comment_authoruser_photo + "' class='photo' width='" + commentObject.comment_authoruser_photo_width + "' border='0'></a></div>";
      else
        newCommentInnerHTML += "<div style='float: left; text-align: center; width: 90px;'><img src='./images/nophoto.gif' class='photo' width='75' border='0'></div>";
      
      newCommentInnerHTML += "<div style='overflow: hidden;'>";
      
      // AUTHOR NAME/LINK
      if( !commentObject.comment_authoruser_id )
        newCommentInnerHTML += "<div class='profile_comment_author'><b>" + bind.Base.Language.Translate(835) + "</b></div>";
      else if( !commentObject.comment_authoruser_exists )
        newCommentInnerHTML += "<div class='profile_comment_author'><b>" + bind.Base.Language.Translate(1071) + "</b></div>";
      else
        newCommentInnerHTML += "<div class='profile_comment_author'><a href='" + commentObject.comment_authoruser_url + "'><b>" + commentObject.comment_authoruser_displayname + "</b></a></div>";
      
      // COMMENT DATE
      newCommentInnerHTML += "<div class='profile_comment_date'>" + commentObject.comment_date + "</div>";
      
      // COMMENT BODY
      newComment.setProperty('html', commentObject.comment_body);
      
      newCommentInnerHTML += "<div class='profile_comment_body' id='profile_comment_body_" + commentID + "'>" + commentObject.comment_body + "&nbsp;</div>";
      newCommentInnerHTML += "<div class='profile_comment_links'>";
      
      // COMMENT LINKS
      var links = new Array();
      if( bind.Base.Viewer.user_exists && commentObject.comment_authoruser_id && commentObject.comment_authoruser_exists )
      {

        // REPLY LINK (VISIBLE ONLY TO OWNER)
	if(bind.options.commentLinks.reply && bind.Base.Viewer.user_info.user_id == bind.Base.Owner.user_info.user_id && bind.Base.Viewer.user_info.user_id != commentObject.comment_authoruser_id) 
        { 
          links.push("<a href='"+commentObject.comment_authoruser_url+querySeparator+"v=comments'>" + bind.Base.Language.Translate(787) + "</a>"); 
        }

	// WALL-TO-WALL (VISIBLE ONLY IF USER CAN SEE AUTHOR'S PROFILE)
	if(bind.options.commentLinks.walltowall && commentObject.comment_authoruser_id != bind.Base.Owner.user_info.user_id && commentObject.comment_authoruser_private == false) 
	{ 
	  links.push("<a href=\"javascript:TB_show('" + bind.Base.Language.Translate(1032) + "', 'profile_comments.php?user=" + bind.Base.Owner.user_info.user_username +"&user2=" + commentObject.comment_authoruser_username + "&TB_iframe=true&height=450&width=550', '', './images/trans.gif');\">" + bind.Base.Language.Translate(891) + "</a>");
        }

        // MESSAGE (VISIBLE IF USER IS NOT AUTHOR)
        if( commentObject.comment_authoruser_id!=bind.Base.Viewer.user_info.user_id )
        {
          links.push("<a href=\"javascript:TB_show('" + bind.Base.Language.Translate(784) + "', 'user_messages_new.php?to_user=" + commentObject.comment_authoruser_displayname + "&to_id=" + commentObject.comment_authoruser_username + "&TB_iframe=true&height=400&width=450', '', './images/trans.gif');\">" + bind.Base.Language.Translate(834) + "</a>");
        }
        
        // EDIT (VISIBLE IF USER IS AUTHOR)
        if( commentObject.comment_authoruser_id==bind.Base.Viewer.user_info.user_id )
        {
          links.push("<a class=\"commentEditLink\" href=\"javascript:void(0);\" id='comment_edit_link_" + commentID + "'>" + bind.Base.Language.Translate(187) + "</a>");
        }
        
      }

      // DELETE (VISIBLE IF USER IS AUTHOR OR USER IS OWNER)
      if((commentObject.comment_authoruser_exists && commentObject.comment_authoruser_id == bind.Base.Viewer.user_info.user_id) || (bind.Base.Viewer.user_exists && bind.Base.Viewer.user_info.user_id == bind.Base.Owner.user_info.user_id))
      {
        links.push("<a class=\"commentDeleteLink\" href=\"javascript:void(0);\" id='comment_delete_link_" + commentID + "'>" + bind.Base.Language.Translate(155) + "</a>");
      }
      
      newCommentInnerHTML += links.join('&nbsp;-&nbsp;');
      newCommentInnerHTML += "&nbsp;</div></div></div>";
      
      // ADD NEW INNERHTML
      newComment.setProperty('html', newCommentInnerHTML);
      newComment.inject(commentContainerElement);
      
      // ADD EVENTS
      if( newComment.getElement('.commentEditLink') ) newComment.getElement('.commentEditLink').addEvent('click', function()
      {
        bind.editComment(commentID);
      });
      
      if( newComment.getElement('.commentDeleteLink') ) newComment.getElement('.commentDeleteLink').addEvent('click', function()
      {
        bind.confirmDelete(commentID);
      });
    });
    
    // CREATE PAGINATION DIV
    if(this.options.paginate && this.total > this.options.cpp) { 
      var commentPaginationTop = new Element('div', {'styles': {'text-align' : 'center'}});
      var commentPaginationBottom = new Element('div', {'styles': {'text-align' : 'center'}});
      if(this.page > 1) {
        var paginationHTMLTop = "<a href='javascript:void(0);' id='comment_last_page_top'>&#171; " + bind.Base.Language.Translate(182) + "</a>";
        var paginationHTMLBottom = "<a href='javascript:void(0);' id='comment_last_page_bottom'>&#171; " + bind.Base.Language.Translate(182) + "</a>";
      } else {
        var paginationHTMLTop = "<font class='disabled'>&#171; " + bind.Base.Language.Translate(182) + "</font>";
        var paginationHTMLBottom = "<font class='disabled'>&#171; " + bind.Base.Language.Translate(182) + "</font>";
      }
      if(p_start == p_end) {
        paginationHTMLTop += "&nbsp;|&nbsp; " + this.Base.Language.TranslateFormatted(184, [p_start, this.total]) + "&nbsp;|&nbsp;";
        paginationHTMLBottom += "&nbsp;|&nbsp; " + this.Base.Language.TranslateFormatted(184, [p_start, this.total]) + "&nbsp;|&nbsp;";
      } else {
        paginationHTMLTop += "&nbsp;|&nbsp; " + this.Base.Language.TranslateFormatted(185, [p_start, p_end, this.total]) + "&nbsp;|&nbsp;";
        paginationHTMLBottom += "&nbsp;|&nbsp; " + this.Base.Language.TranslateFormatted(185, [p_start, p_end, this.total]) + "&nbsp;|&nbsp;";
      }
      if(this.page != maxpage) {
        paginationHTMLTop += "<a href='javascript:void(0);' id='comment_next_page_top'>" + bind.Base.Language.Translate(183) + " &#187;</a>";
        paginationHTMLBottom += "<a href='javascript:void(0);' id='comment_next_page_bottom'>" + bind.Base.Language.Translate(183) + " &#187;</a>";
      } else {
        paginationHTMLTop += "<font class='disabled'>" + bind.Base.Language.Translate(183) + " &#187;</font>";
        paginationHTMLBottom += "<font class='disabled'>" + bind.Base.Language.Translate(183) + " &#187;</font>";
      }
      commentPaginationTop.setProperty('html', paginationHTMLTop);
      commentPaginationBottom.setProperty('html', paginationHTMLBottom);
      commentPaginationTop.inject(commentContainerElement, 'top');
      commentPaginationBottom.inject(commentContainerElement);

      // ADD EVENTS
      if( commentPaginationTop.getElement('a[id=comment_last_page_top]') ) commentPaginationTop.getElement('a[id=comment_last_page_top]').addEvent('click', function()
      {
        bind.getComments('previous');
      });

      if( commentPaginationBottom.getElement('a[id=comment_last_page_bottom]') ) commentPaginationBottom.getElement('a[id=comment_last_page_bottom]').addEvent('click', function()
      {
        bind.getComments('previous');
      });
      
      if( commentPaginationTop.getElement('a[id=comment_next_page_top]') ) commentPaginationTop.getElement('a[id=comment_next_page_top]').addEvent('click', function()
      {
        bind.getComments('next');
      });

      if( commentPaginationBottom.getElement('a[id=comment_next_page_bottom]') ) commentPaginationBottom.getElement('a[id=comment_next_page_bottom]').addEvent('click', function()
      {
        bind.getComments('next');
      });
    }

  },
  
  
  // Adds a comment
  addComment: function(is_error, comment_body, comment_date)
  {
    if( !this.options.canComment )
      return false;
    
    if( is_error )
    {
      $('comment_error').style.display = 'block';
      if( !comment_body.trim() )
      {
        this.addText($('comment_body'));
        $('comment_error').innerHTML = this.Base.Language.Translate(831);
      }
      else
      {
        $('comment_error').innerHTML = this.Base.Language.Translate(832);
      }
      $('comment_submit').value = "Post Comment";
      $('comment_submit').disabled = false;
    }
    else
    {
      $('comment_error').style.display = 'none';
      $('comment_error').innerHTML = '';
      
      $('comment_body').value = '';
      $('comment_body').style.height = this.options.originalHeight + 'px';
      this.addText($('comment_body'));
      
      $('comment_submit').value = "Post Comment";
      $('comment_submit').disabled = false;
      
      if( $('comment_secure') )
      {
        $('comment_secure').value = '';
        $('secure_image').src = $('secure_image').src + '?' + (new Date()).getTime();
      }
      
      // INPUT COMMENTS
      this.page = 1;
      this.total++;
      this.getComments();
    }
  },
  
  
  
  editComment: function(commentID)
  {
    var bind = this;
    if( this.isEditing ) return false;
    this.isEditing = true;
    
    
    //var commentContainerElement = $(this.options.type + '_' + this.options.typeID + '_comments');
    //var commentElement = commentContainerElement.getElement('profile_comment_body_' + commentID);
    var commentElement = $('profile_comment_body_' + commentID);
    
    var height = commentElement.offsetHeight + 10;
    var commentText = commentElement.innerHTML.replace(/<br>/gi, '\r\n').replace(/>/gi, '&gt;');
    
    var innerHTML = '';
    innerHTML += "<form action='misc_js.php' method='post' target='ajaxframe' name='editCommentForm'>";
    innerHTML += "<textarea name='comment_edit' id='comment_edit_" + commentID + "' style='height: " + height +" px; width: 100%;'>" + commentText + "</textarea>";
    innerHTML += "<input type='hidden' name='task' value='comment_edit'>";
    innerHTML += "<input type='hidden' name='comment_id' value='" + commentID + "'>";
    innerHTML += "<input type='hidden' name='type' value='" + this.options.type + "'>";
    innerHTML += "<input type='hidden' name='iden' value='" + this.options.typeIdentifier + "'>";
    innerHTML += "<input type='hidden' name='value' value='" + this.options.typeID + "'>";
    
    if( this.options.typeTab ) innerHTML += 
        '<input type="hidden" name="tab" value="' + this.options.typeTab + '">';
    
    if( this.options.typeCol ) innerHTML += 
        '<input type="hidden" name="col" value="' + this.options.typeCol + '">';
    
    if( this.options.typeTabParent ) innerHTML += 
        '<input type="hidden" name="tab_parent" value="' + this.options.typeTabParent + '">';
    
    if( this.options.typeColParent ) innerHTML += 
        '<input type="hidden" name="col_parent" value="' + this.options.typeColParent + '">';
    
    if( this.options.typeChild ) innerHTML += 
        '<input type="hidden" name="child" value="1">';
    
    
    innerHTML += "</form>";
    
    
    // Inject
    commentElement.innerHTML = innerHTML;
    textarea_autogrow('comment_edit_' + commentID);
    $('comment_edit_' + commentID).focus();
    
    
    // Add events
    $('comment_edit_' + commentID).addEvent('blur', function()
    {
      document.editCommentForm.submit();
      bind.isEditing = false;
    });
  },
  
  
  
  confirmDelete: function(commentID)
  {
    $('del_comment_id').value = commentID;
    TB_show(this.Base.Language.Translate(1025), '#TB_inline?height=100&width=300&inlineId=confirmcommentdelete', '', '../images/trans.gif');
  },
  
  
  
  
  
  
  
  // UI Methods
  removeText: function(commentBody)
  {
    if( !this.changed )
    {
      commentBody.value = '';
      commentBody.style.color = '#000000';
      this.changed = true;
    }
  },
  
  
  
  addText: function(commentBody)
  {
    if( !commentBody.value.trim() )
    {
      commentBody.value = "Post Comment";
      commentBody.style.color = '#888888';
      this.changed = false;
    }
  },
  
  
  
  checkText: function(commentBody)
  {
    if( !this.changed )
      $('comment_body').value='';
    
    $('comment_submit').value = this.Base.Language.Translate(830);
    $('comment_submit').disabled = true;
  }
  
});*/

/* end class_comments
start class_core.js comments */


/*SocialEngineAPI.Core = new Class({
  
  // Properties
  Base: {},
  
  settings: {},
  
  plugins: {},
  
  options : {
    ajaxURL : 'js_api.php'
  },

  
  
  
  // Methods
  initialize: function()
  {
    
  },

  
  
  
  // Import Methods
  ImportSettings: function(settings)
  {
    this.settings = settings;
  },

  
  
  
  // Import Methods
  ImportPlugins: function(plugins)
  {
    this.plugins = plugins;
  }
  
});*/

/* end class_core.js file
start class_tag.js */


// Required language variables: 39,1212,1213,1214,1215,1228

/*SocialEngineAPI.Tags = new Class({
  
  // Class
	//Implements: [Options],
  
  // Properties
  Base: {},
  
  isTagging: false,

  newtag : false,

  tags : [],
  
  
  options: {
    // Controls ajax request options
    'ajaxURL' : 'misc_js.php',
    'ajaxMethod' : 'post',
    'ajaxSecure' : false,
    
    // Can the viewer media
    'canTag' : false,
    
    // The type of media ex. 'group'
    'type' : false,
    
    // The actual ID of the object being tagged
    'media_id' : false,

    // Path to the image
    'media_dir' : false,
    
    // Some other stuff to identify the object
    'object_owner' : false,
    'object_owner_id' : false
  },
  
  
  
  
  // Methods
  initialize: function(options)
  {
    this.setOptions(options);
    
    if( this.options.initialTotal ) this.total = this.options.initialTotal;

    var bind = this;
    window.addEvent('domready', function()
    {
      bind.showTagForm();
    });
  },
  
  
  
  showTagForm : function()
  {
    var innerHTML = "";
    var bind = this;

    if( this.options.canTag ) 
    {
      innerHTML +=
	"<div class='media_photo_tagform_titlebar'><img src='images/icons/photos16.gif' class='icon' />" + this.Base.Language.Translate(1212) + "</div>" +
	"<div style='padding: 7px;'>" +
	"<div style='text-align: left;'>" +
	"<div style='font-size: 7pt; margin-bottom: 5px;'>" + this.Base.Language.Translate(1213) + "</div>" +
	"<div style='text-align: center;'><input type='text' style='width: 130px; padding-left: 4px; font-size: 8pt;' name='media_photo_tag' id='media_photo_tag' class='text' maxlength='40'/></div>" +
	"</div>" +
	"<div id='media_photo_friendlist' class='media_photo_friendlist'>";

      if( bind.Base.Viewer.user_exists ) 
      {
        innerHTML += "<div><a href='javascript:void(0)' id='tag_me'>" + bind.Base.Viewer.user_displayname + bind.Base.Language.Translate(1214) + "</a></div>";
      }

      innerHTML += "</div>" +
        "<div>" +
	"<input type='button' class='button' name='save' id='tag_save' value='" + bind.Base.Language.Translate(1215) + "' />&nbsp;&nbsp;" +
	"<input type='button' class='button' id='tag_cancel' name='cancel' value='" + bind.Base.Language.Translate(39) + "' />" +
	"</div>" +
        "</div>";

      var newTagForm = new Element('div', {
        'id' : 'media_photo_tagform',
        'class' : 'media_photo_tagform',
        'html' : innerHTML
      });

      var mediaContainer = $('media_photo_div');
      newTagForm.inject(mediaContainer);

      // ADD EVENTS
      if( newTagForm.getElement('input[id=tag_cancel]') ) newTagForm.getElement('input[id=tag_cancel]').addEvent('click', function()
      {
        bind.cancelTag();
      });
      if( newTagForm.getElement('input[id=tag_save]') ) newTagForm.getElement('input[id=tag_save]').addEvent('click', function()
      {
        bind.saveTag(0);
      });
      if( newTagForm.getElement('a[id=tag_me]') ) newTagForm.getElement('a[id=tag_me]').addEvent('click', function()
      {
        bind.saveTag(bind.Base.Viewer.user_info.user_id);
      });

      var request = new Request.JSON({secure: false, url: 'misc_js.php?task=friends_all',
		onComplete: function(jsonObj) { 
			bind.addFriendToList(jsonObj.friends);
		}
      }).send();
    }
  },
  
  
  
  addFriendToList : function(friends)
  {
    var bind = this;

    friends.each(function(friend) {
      for(var x in friend) {

	var newDiv = new Element("div", {'id' : 'friend_div_'+x});
	var newAnchor = new Element("a", {'href' : 'javascript:void(0)', 
			'id' : 'friend_link_'+x,
			'html' : friend[x]
		}).inject(newDiv);

	newDiv.inject($('media_photo_friendlist'));

	$('friend_link_'+x).addEvent('click', function() { bind.saveTag(x); });
      }
    });
  },
  
  
  
  insertTag : function(tag_id, tag_link, tag_text, tag_x, tag_y, tag_width, tag_height, tagged_user)
  {
    var newHTML = '';
    var bind = this;

    if($('media_tags').style.display == 'none') 
    {
      $('media_tags').style.display = 'block';
    } else if(bind.tags.length != 0) 
    {
      newHTML = '<span id="tag_comma_'+tag_id+'">, </span>';
    }

    var newSpan = new Element("span", {'id' : 'full_tag_'+tag_id, 'html' : newHTML});
    if(tag_link != '') 
    {
      var newAnchor = new Element("a", {'href' : tag_link, 
			'id' : 'tag_link_'+tag_id,
			'html' : tag_text
		}).inject(newSpan);
    } 
    else {
      var newAnchor = new Element("span", {'id' : 'tag_link_'+tag_id,
				'html' : tag_text,
				'styles' : {'cursor' : 'pointer'}
			}).inject(newSpan);
    } 

    if( bind.Base.Viewer.user_exists && (bind.Base.Viewer.user_info.user_username == tagged_user || bind.Base.Viewer.user_info.user_username == bind.Base.Owner.user_info.user_username)) 
    {
      var media_tags_text = $(newSpan).get('html');
      $(newSpan).set('html', media_tags_text, ' (<a href=\'javascript:void(0);\' id=\'new_removetag_link\'>' + bind.Base.Language.Translate(1228) + '</a>)');
    }

    newSpan.inject($('media_tags'));

    bind.createTag(tag_id, tag_text, tag_x, tag_y, tag_width, tag_height);

    $('tag_link_'+tag_id).addEvent('mouseover', function() { bind.showTag(tag_id); });
    $('tag_link_'+tag_id).addEvent('mouseout', function() { bind.hideTag(tag_id); });

    if($('new_removetag_link')) {
      $('new_removetag_link').addEvent('click', function() { bind.removeTag(tag_id); });
      $('new_removetag_link').set('id', 'removetag_link_'+tag_id);
    }

    bind.tags.push(tag_id);
  },
  
  
  
  createTag : function(tag_id, label_text, tag_x, tag_y, tag_width, tag_height)
  {
    var bind = this;
  
    // CREATE TAG AND LABEL
    new Element("div", {'id' : 'tag_'+tag_id, 'html' : '<img src="./images/trans.gif" width="100%" height="100%" />', 'class' : 'tag_div_hidden', 'styles' : {'width' : (parseInt(tag_width)-4)+'px', 'height' : (parseInt(tag_height)-4)+'px', 'top' : tag_x+'px', 'left' : tag_y+'px'}}).inject($('media_photo_div'));
    new Element("div", {'id' : 'tag_label_'+tag_id, 'html' : label_text, 'class' : 'tag_label', 'styles' : {'display' : 'none', 'top' : (parseInt(tag_x)+parseInt(tag_height)+10)+'px', 'left' : tag_y+'px'}}).inject($('media_photo_div'));

    // ADD MOUSEOVER/MOUSEOUT EVENTS
    $('tag_'+tag_id).addEvent('mouseover', function() { bind.showTag(tag_id); });
    $('tag_'+tag_id).addEvent('mouseout', function() { bind.hideTag(tag_id); });
  },
  
  
  
  showTag : function(tag_id)
  {
    $('tag_'+tag_id).className = 'tag_div';
    $('tag_label_'+tag_id).style.display = 'block';
  },
  
  
  
  hideTag : function(tag_id)
  {
    $('tag_'+tag_id).className = 'tag_div_hidden';
    $('tag_label_'+tag_id).style.display = 'none';
  },
  
  
  
  addTag : function()
  {
    if(!this.isTagging) {
      this.isTagging = true;
      this.newtag = new MooCrop('media_photo');
 
      var bind = this;

      var indicator = $('media_photo_tagform').inject(bind.newtag.wrapper);
      indicator.setStyles({'top' : this.newtag.crop.bottom+10, 'left' : this.newtag.crop.right+10, 'display' : 'block'});

      this.newtag.addEvent('onBegin', function(imgsrc, crop, bound, hanlde) { indicator.setStyle('display', 'none'); });
      this.newtag.addEvent('onCrop', function(imgsrc, crop, bound, hanlde) { indicator.setStyles({'top' : crop.bottom+10, 'left' : crop.right+10, 'display' : 'none'}); });
      this.newtag.addEvent('onComplete', function(imgsrc, crop, bound, hanlde) { indicator.setStyle('display', 'block'); });
    }
  },
  
  
  
  cancelTag : function()
  {
    if(this.isTagging) {
      $('media_photo_tag').value = '';
      $('media_photo_tagform').inject('media_photo_div').setStyle('display', 'none');
      var stopTagging = this.newtag.removeOverlay.bind(this.newtag);
      stopTagging();
      this.isTagging = false;
    }
  },
  
  
  
  saveTag : function(mediatag_user_id)
  {
    if(this.isTagging) {

      if( this.options.object_owner && this.options.object_owner_id )
      {
        var object_owner = this.options.object_owner;
        var object_owner_id = this.options.object_owner_id;
        var user = '';
      } else {
        var object_owner = '';
        var object_owner_id = '';
        var user = this.Base.Owner.user_info.user_username;      
      }

      var url = "misc_js.php?task=tag_do" +
                "&mediatag_user_id=" + mediatag_user_id +
		"&mediatag_text=" + encodeURIComponent($('media_photo_tag').value) +
		"&mediatag_x=" + this.newtag.crop.top +
		"&mediatag_y=" + this.newtag.crop.left +
		"&mediatag_height=" + this.newtag.crop.height +
		"&mediatag_width=" + this.newtag.crop.width +
		"&user=" + user +
		"&object_owner=" + object_owner +
		"&object_owner_id=" + object_owner_id +
		"&type=" + this.options.type +
		"&media_id=" + this.options.media_id +
		"&media_dir=" + this.options.media_dir;

      $('ajaxframe').src = url;

      $('media_photo_tag').value = '';
      $('media_photo_tagform').inject('media_photo_div').setStyle('display', 'none');
      var stopTagging = this.newtag.removeOverlay.bind(this.newtag);
      stopTagging();
      this.isTagging = false;
    }
  },
  
  
  
  removeTag : function(tag_id)
  {

    if( this.options.object_owner && this.options.object_owner_id )
    {
      var object_owner = this.options.object_owner;
      var object_owner_id = this.options.object_owner_id;
      var user = '';
    } else {
      var object_owner = '';
      var object_owner_id = '';
      var user = this.Base.Owner.user_info.user_username;      
    }

    var url = "misc_js.php?task=tag_remove" +
                "&mediatag_id=" + tag_id +
		"&user=" + user +
		"&object_owner=" + object_owner +
		"&object_owner_id=" + object_owner_id +
		"&type=" + this.options.type +
		"&media_id=" + this.options.media_id;

    $('ajaxframe').src = url;

    $('tag_'+tag_id).destroy();
    $('tag_label_'+tag_id).destroy();

    $('full_tag_'+tag_id).destroy();

    if(this.tags.indexOf(tag_id) == 0 && $('tag_comma_'+this.tags[1])) {
      $('tag_comma_'+this.tags[1]).destroy();
    }

    this.tags.splice(this.tags.indexOf(tag_id), 1);

    if(this.tags.length == 0) {
      $('media_tags').style.display = 'none';
    }
  }


  
});*/


/***
 * MooCrop (v. rc-1 - 2007-10-24 )
 *
 * @version			rc-1
 * @license			BSD-style license
 * @author			nwhite - < nw [at] nwhite.net >
 * @infos			http://www.nwhite.net/MooCrop/
 * @copyright		Author
 * 

 */
/*var MooCrop = $j.Class.extend("MooCrop",{

	calculateHandles : true,
	current : {},

	options : {
		maskColor : 'black',
		maskOpacity : '.3',
		handleColor : '#FFFFFF',
		handleWidth : '5px',
		handleHeight : '5px',
		cropBorder : '1px dashed #FFFFFF',
		min : { 'width' : 50, 'height' : 50 },
		showMask : true, // false to remove, helps on slow machines
		showHandles : false // hide handles on drag
	},

	initialize: function(el, options){
		this.setOptions(options);
		this.img = $(el);
		if ( this.img.get('tag') != 'img') return false;

		this.resizeFunc = this.refresh.bindWithEvent(this);
		this.removeFunc = this.removeListener.bind(this);

		this.buildOverlay();
		this.setup();
	},

	setup: function(){
		$(this.cropArea).setStyles({
			'width': this.options.min.width, 
			'height': this.options.min.height,
			'top' : (this.img.height - this.options.min.height)/2,
			'left': (this.img.width - this.options.min.width) / 2 
		});

		this.current.crop = this.crop = this.getCropArea();
		this.handleWidthOffset = this.options.handleWidth.toInt() / 2;
		this.handleHeightOffset = this.options.handleHeight.toInt() /2;

		this.fixBoxModel();
		this.drawMasks();
		this.positionHandles();
	},

	getCropArea : function(){
		var crop = this.cropArea.getCoordinates();
		crop.left -= this.offsets.x; crop.right -= this.offsets.x; // calculate relative (horizontal)
		crop.top -= this.offsets.y; crop.bottom  -= this.offsets.y; // calculate relative (vertical)
		return crop;
	},

	fixBoxModel : function(){
		var diff = this.boxDiff = (this.crop.width - this.options.min.width)/2;

		var b = this.bounds = { 'top' : diff, 'left' : diff, 
			'right' : this.img.width+(diff*2), 'bottom' : this.img.height+(diff*2),
			'width' : this.options.min.width+(diff*2), 'height' : this.options.min.height+(diff*2) };

		this.wrapper.setStyles({
			'width' : b.right, 'height' : b.bottom,
			'background' : 'url('+this.img.src+') no-repeat '+diff+'px '+diff+'px'
		});

		this.north.setStyle('width',b.right);
		this.south.setStyle('width',b.right);
	},

	activate : function(event,handle){
		event.stop();
		this.current = { 'x' : event.page.x, 'y' : event.page.y, 'handle' : handle, 'crop' : this.current.crop };
		if(this.current.handle == 'NESW' && !this.options.showHandles) this.hideHandles();
		this.fireEvent('onBegin',[this.img.src,this.getCropInfo(),this.bounds,handle]);
		document.addEvent('mousemove', this.resizeFunc);
		document.addEvent('mouseup', this.removeFunc);
	},

	removeListener : function(){
		if( this.current.handle == 'NESW' && !this.options.showHandles) this.showHandles();
		document.removeEvent('mousemove', this.resizeFunc);
		document.removeEvent('mouseup', this.removeFunc);
		this.crop = this.current.crop;
		this.fireEvent('onComplete',[this.img.src,this.getCropInfo(),this.bounds,this.current.handle]);
	},

	refresh : function(event){
		var xdiff = this.current.x - event.page.x;
		var ydiff = this.current.y - event.page.y;

		var b = this.bounds;  var c = this.crop;  var handle = this.current.handle; var styles = {}; //saving bytes
		var dragging = (handle.length > 2) ? true : false;
		
		if( handle.contains("S") ){//SOUTH
			if(c.bottom - ydiff > b.bottom ) ydiff = c.bottom - b.bottom; // box south
			if(!dragging){
				if( (c.height - ydiff) < b.height ) ydiff = c.height - b.height; // size south
				styles['height'] = c.height - ydiff; // South handles only
			}
		}
		if( handle.contains("N") ){//NORTH
			if(c.top - ydiff < b.top ) ydiff = c.top; //box north
			if(!dragging){
				if( (c.height + ydiff ) < b.height ) ydiff = b.height - c.height; // size north
				styles['height'] = c.height + ydiff; // North handles only
			}
			styles['top'] = c.top - ydiff; // both Drag and N handles
		}
		if( handle.contains("E") ){//EAST
			if(c.right - xdiff > b.right) xdiff = c.right - b.right; //box east
			if(!dragging){
				if( (c.width - xdiff) < b.width ) xdiff = c.width - b.width; // size east
				styles['width'] = c.width - xdiff;
			}
		}
		if( handle.contains("W") ){//WEST
			if(c.left - xdiff < b.left) xdiff = c.left; //box west
			if(!dragging){
				if( (c.width + xdiff) < b.width ) xdiff = b.width - c.width; //size west
				styles['width'] = c.width + xdiff;
			}
			styles['left'] = c.left - xdiff; // both Drag and W handles
		}
		var preCssStyles = $merge(styles);
		if( $defined(styles.width)) styles.width -= this.boxDiff*2;
		if( $defined(styles.height)) styles.height -= this.boxDiff*2;

		this.cropArea.setStyles(styles);
		this.getCurrentCoords(preCssStyles);
		this.drawMasks();
		this.positionHandles();
		this.fireEvent('onCrop',[this.img.src,this.getCropInfo(),b,handle]);
	},

	getCurrentCoords : function(changed){
		var current = $merge(this.crop);
		
		if($defined(changed.left)){
			current.left = changed.left;
			if($defined(changed.width)) current.width = changed.width;
			else current.right = current.left + current.width;
		}
		if($defined(changed.top)){
			current.top = changed.top;
			if($defined(changed.height)) current.height = changed.height;
			else current.bottom = current.top + current.height;
		}
		if($defined(changed.width) && !$defined(changed.left)){
			current.width = changed.width; current.right = current.left + current.width;
		}
		if($defined(changed.height) && !$defined(changed.top)){
			current.height = changed.height; current.bottom = current.top + current.height;
		}
		this.current.crop = current;
	},

	drawMasks : function(){
		if(!this.options.showMask) return;
		var b = this.bounds;  var c = this.current.crop; var handle = this.current.handle;

		this.north.setStyle('height', c.top + 'px' );
		this.south.setStyle('height', b.bottom  - c.bottom  + 'px');
		this.east.setStyles({ height: c.height + 'px', width: b.right  - c.right + 'px',  top: c.top  + 'px', left: c.right + 'px'});
		this.west.setStyles({ height: c.height + 'px', width: c.left + 'px', top: c.top + 'px'});
	},

	positionHandles: function(){
		if(!this.calculateHandles) return;
		var c = this.current.crop; var wOffset = this.handleWidthOffset; var hOffset = this.handleHeightOffset;

		this.handles.get('N').setStyles({'left' : c.width / 2 - wOffset + 'px', 'top' : - hOffset + 'px'});
		this.handles.get('NE').setStyles({'left' : c.width - wOffset + 'px', 'top' : - hOffset + 'px'});
		this.handles.get('E').setStyles({ 'left' : c.width - wOffset + 'px', 'top' : c.height / 2 - hOffset + 'px'});
		this.handles.get('SE').setStyles({'left' : c.width - wOffset + 'px', 'top' : c.height - hOffset + 'px'});
		this.handles.get('S').setStyles({'left' : c.width / 2 - wOffset + 'px', 'top' : c.height - hOffset + 'px'});
		this.handles.get('SW').setStyles({'left' : - wOffset + 'px', 'top' : c.height - hOffset + 'px'});
		this.handles.get('W').setStyles({'left' : - wOffset + 'px', 'top' : c.height / 2 - hOffset + 'px'});
		this.handles.get('NW').setStyles({'left' : - wOffset + 'px', 'top' : - hOffset + 'px'});
	},

	hideHandles: function(){
		this.calculateHandles = false;
		this.handles.each(function(handle){
			handle.setStyle('display','none');
		});
	},

	showHandles: function(){
		this.calculateHandles = true;
		this.positionHandles();
		this.handles.each(function(handle){
			handle.setStyle('display','block');
		});
	},

	buildOverlay: function(){
		var o = this.options;

		this.wrapper = new Element("div", {
			'styles' : {'z-index' : 100, 'position' : 'relative', 'width' : this.img.width, 'height' : this.img.height, 'background' : 'url('+this.img.src+') no-repeat' , 'float' : this.img.getStyle('float') , 'margin-left' : 'auto' , 'margin-right' : 'auto'  }
		}).injectBefore(this.img);

		this.img.setStyle('display','none');

		this.offsets = { x : this.wrapper.getLeft(), y : this.wrapper.getTop() };

		// SET WRAPPER MOUSEOVER TO STOP PROPAGATION OF MOUSEOVER EVENT
		this.wrapper.addEvent('mouseover', function(event) { return false; });

		if(this.options.showMask){		// optional masks
			var maskStyles = { 'position' : 'absolute', 'overflow' : 'hidden', 'background-color' : o.maskColor, 'opacity' : o.maskOpacity};
			this.north = new Element("div", {'styles' : $merge(maskStyles,{'left':'0px'})}).injectInside(this.wrapper);
			this.south = new Element("div", {'styles' : $merge(maskStyles,{'bottom':'0px', 'left':'0px'})}).injectInside(this.wrapper);
			this.east =  new Element("div", {'styles' : maskStyles}).injectInside(this.wrapper);
			this.west =  new Element("div", {'styles' : $merge(maskStyles,{'left':'0px'})}).injectInside(this.wrapper);
		}

		this.cropArea = new Element("div", { 'styles' : { 'position' : 'absolute', 'top' : '0px', 'left' : '0px', 'border' : o.cropBorder, 'cursor' : 'move' },
		'events' : {
			'dblclick' : function(){ this.fireEvent('onDblClk',[this.img.src,this.getCropInfo(),this.bounds])}.bind(this),
			'mousedown' : this.activate.bindWithEvent(this,'NESW')}
		}).injectInside(this.wrapper);

		this.handles = new Hash();
		['N','NE','E','SE','S','SW','W','NW'].each(function(handle){
			this.handles.set(handle, new Element("div", {
			'styles' : { 'position' : 'absolute', 'background-color' : o.handleColor, 
						 'width' : o.handleWidth, 'height' : o.handleHeight, 'overflow' : 'hidden', 'cursor' : (handle.toLowerCase()+'-resize')},
			'events' : {'mousedown' : this.activate.bindWithEvent(this,handle)}
			}).injectInside(this.cropArea));
		},this);
	},

	getCropInfo : function(){
		var c = $merge(this.current.crop);
		c.width -= this.boxDiff*2; c.height -= this.boxDiff*2;
		return c;
	},

	removeOverlay: function(){
		this.wrapper.destroy();
		this.img.setStyle('display','');
	}

});*/

//MooCrop.implement(new Events, new Options);

/* end class_tag.js
start class_url.js */


/*SocialEngineAPI.URL = new Class({
  
  // Properties
  Base: {},
  
  url_base : null,
  
  url_info : {},
  
  
  
  // Methods
  initialize: function()
  {
    
  },
  
  
  url_create: function(name, user, id1, id2, id3)
  {
    var url_template = ( SocialEngine.Core.settings.setting_url ? this.url_info[name].url_subdirectory : this.url_info[name].url_regular );
    if( !url_template ) return false;
    
    url_template = url_template.replace('$user', user);
    url_template = url_template.replace('$id1', id1);
    url_template = url_template.replace('$id2', id2);
    url_template = url_template.replace('$id3', id3);
    
    return this.url_base + url_template;
  },
  
  
  url_userdir: function(user_id)
  {
    //alert(user_id + ' ' + ((user_id - 1) % 1000).toString());
    return 'uploads_user/' + (user_id + 999 - ((user_id - 1) % 1000)).toString() + '/' + user_id + '/';
  },
  
  
  
  
  
  // Import methods
  ImportURLBase: function(url_base)
  {
    this.url_base = url_base;
  },
  
  ImportURLInfo: function(url_info)
  {
    this.url_info = url_info;
  }
  
  
});*/

/* end class_url.js 
start class_user.js*/


/*SocialEngineAPI.User = new Class({
  
  // Properties
  Base: {},
  
  user_exists : false,
  
  user_displayname : false,
  
  user_displayname_short : false,
  
  user_info : {},
  
  profile_info : {},
  
  level_info : {},
  
  usersetting_info : {},
  
  options : {
    'displayname_order' : 'standard'
  },
  
  
  
  // Methods
  initialize: function()
  {
    
  },
  
  
  userPhotoFullPath: function()
  {
    // No URL class
    if( !this.Base.URL )
      return false;
    
    // No user photo
    if( !this.user_info.user_photo )
      return this.Base.URL.url_base + 'images/nophoto.gif';
      
    return this.Base.URL.url_base + this.Base.URL.url_userdir(this.user_info.user_id) + this.user_info.user_photo;
  },
  
  
  
  
  
  // Import methods
  ImportUserInfo: function(user_info)
  {
    // Handle anonymous users
    if( !user_info || $type(user_info)!="object" || !user_info.user_exists )
    {
      this.user_exists = false;
      return;
    }
    
    this.user_exists = true;
    
    // Prepare data
    user_info.user_id = parseInt(user_info.user_id);
    delete user_info.user_exists;
    
    // Save user info
    this.user_info = user_info;
    
    // Generate display name
    this.user_info.user_fname = this.user_info.user_fname.trim();
    this.user_info.user_lname = this.user_info.user_lname.trim();
    
    if( this.user_info.user_fname && this.user_info.user_lname )
    {
      // Asian
      if( this.options.displayname_order=="asian" )
      {
        this.user_displayname_short = this.user_info.user_lname;
        this.user_displayname = this.user_info.user_lname + ' ' + this.user_info.user_fname;
      }
      
      // Standard
      else
      {
        this.user_displayname_short = this.user_info.user_fname;
        this.user_displayname = this.user_info.user_fname + ' ' + this.user_info.user_lname;
      }
    }
    
    else if( this.user_info.user_fname )
    {
      this.user_displayname = this.user_displayname_short = this.user_info.user_fname;
    }
    
    else if( this.user_info.user_lname )
    {
      this.user_displayname = this.user_displayname_short = this.user_info.user_lname;
    }
    
    else if( this.user_info.user_username )
    {
      this.user_displayname = this.user_displayname_short = this.user_info.user_username;
    }
  }
  
});*/

/* end class_user.js
start class_language.js*/

/*if( typeof(SocialEngineAPI)=="undefined" )
  var SocialEngineAPI = {};

SocialEngineAPI.Language = new Class({
  
  // Properties
  Base: {},

  
  
  
  // Methods
  initialize: function()
  {
    this.languageVariables = new Hash();
  },
  
  
  Translate: function(id)
  {
	  	
    var rawValue = this.languageVariables.get(id) || 'Missing Language Variable #' + id;
    return rawValue;
  },
  
  
  TranslateFormatted: function(id, params)
  {
    var rawValue = this.languageVariables.get(id) || 'Missing Language Variable #' + id;
    params.unshift(rawValue);
    var formattedValue = sprintf.run(params);
    return formattedValue;
  },
  
  
  
  
  // Import Methods
  Import: function(languageVariableObject)
  {
    if( $type(languageVariableObject)=="object" )
      this.languageVariables.extend(languageVariableObject);
  }
  
});*/

  /*for  common header */
	  function doSearch_Btn(search_res)
	  {
	   var search_val = $j('#search').val();
	   var redi = 0;
	   
	   if(search_val=='Find Entertainment...' || search_val=='What would you like to say?')
	   {
	   		search_val = $j('#search3').val();
			if(search_val=='' || search_val=='Search &amp; Watch TV Shows - Movies' || search_val=='Search and Watch TV shows' || search_val=='Search and Watch Movies' )
			{
			 return false;
			 }
			 else
			 {
			 	redi = 1;
			 }
		   
		}
		else
		{
		redi = 1;
		}
		
		if(redi == 1)
		{
			 var redirect_url = 'http://'+tube_hostname+search_res;
			 document.location = redirect_url;
			 redirected = 1;
		 }
		
	  }
	     function search_button()
		{
			var field_value = document.getElementById('search4').value;
			doSearch(field_value,1,false);	
		}

	  function search_suggest(inputShow) {
		if(inputShow.length == 0) {
			// Hide the suggestion box.
			$j('#search_query_auto_complete').hide();
		} else {
			$j.post("showrec.php", {queryString: ""+inputShow+""}, function(data){
				if(data.length >0) {
					$j('#search_query_auto_complete').show();
					$j('#search_query_auto_completeul').html(data);
					$j('#search').blur(function(){$j('#search_query_auto_complete').hide("slow");});
				}
			});
		}
	} // lookup
	function search_item(inputText)
	{
		$j('#search').val(inputText);
		$j('#search_query_auto_complete').hide();
		doSearchBtn('search-top-form','all');
		
	}
	function disappear_search_item(div_id)
	{
		$j('#'+div_id).hide();
		
	}

	function emailondone()
	{
	  document.location = document.location.href;
	}
	function openemailpopup()
	{
	 FB.Connect.showPermissionDialog('email', emailondone,null,null);
	}

	function ShowHideDeps(field_id, field_value, field_type) {
	if(field_type == 6) {
      if($('field_'+field_id+'_option'+field_value)) {
        if($('field_'+field_id+'_option'+field_value).style.display == "block") {
	  $('field_'+field_id+'_option'+field_value).style.display = "none";
	} else {
	  $('field_'+field_id+'_option'+field_value).style.display = "block";
	}
      }
    } else {
      var divIdStart = "field_"+field_id+"_option";
      for(var x=0;x<$('field_options_'+field_id).childNodes.length;x++) {
        if($('field_options_'+field_id).childNodes[x].nodeName == "DIV" && $('field_options_'+field_id).childNodes[x].id.substr(0, divIdStart.length) == divIdStart) {
          if($('field_options_'+field_id).childNodes[x].id == 'field_'+field_id+'_option'+field_value) {
            $('field_options_'+field_id).childNodes[x].style.display = "block";
          } else {
            $('field_options_'+field_id).childNodes[x].style.display = "none";
          }
        }
      }
    }
  }
  function verify_user(){
	$j('#email_verified').css('width','450px');
	$j('#email_verified').modal({overlayClose:true, zIndex:999999999, persist:true});
    return false;
}
function verify_security_code(text){
    $j("#redemption_txt").val(text);
	var htm = '<b>Please verify the following captcha to confirm your redemption of Yidio Credits for ' + text + '</b>'; 
    $j('#secucor_overlay_text').html(htm);  
	$j('#security_code_verified').css('width','450px');
	$j('#security_code_verified').modal({overlayClose:true, zIndex:999999999, persist:true});
    return false;
}
function chk_redem()
{
	var numericExpression = /^[0-9]+$/;
	var flag = 0;
	var invite_secure = $j("#invite_secure").val();
	if(invite_secure != ''){
	     if(numericExpression.test(invite_secure) == false){
		   flag = 1;
		   alert("Numbers are only accepted in security Code.");
		   return false;
	     }
	} else {
	     alert('Please enter security code');
	     flag = 1;
	     return false;
	}
	//if no error 
	if(flag == 0)
	{
		var text =$j("#redemption_txt").val();
		$j.ajax({
				   type: "GET",
				   url: "/ajax_user_points_shop_securitycode.php",
				   data: "invite_secure="+invite_secure,
				   success: function(response){
				      //$j("#invite_secure").val('');
					  if(response.match("error"))
						 alert('Your verification code not correct. please correct it.');
					  else{
						 //if(confirm("Please confirm your redemption of Yidio Credits for a " + text))
						    $j('#myform').submit();
				      }
				 }
			 });
	}	 
}
function resizeFrame() {
	document.getElementById("offerpal").style.height = document.getElementById("offerpal").contentWindow.document.body.scrollHeight + "px";
}
function showhide(id1) {
	if(document.getElementById(id1).style.display=='none') {
		
		document.getElementById("img_"+id1).src="images/bul-episodes-hover.gif";
		document.getElementById(id1).style.display='block';
	} else {
		
		document.getElementById("img_"+id1).src="images/bul-episodes.gif";
		document.getElementById(id1).style.display='none';
	}
}
function show_pop(eid)
{
	if(eid > 0)
	parent.TB_show2('', 'redeem_pop.php?tran_id={/literal}{$trans_id}{literal}&e_id={/literal}{$e_id}{literal}&TB_iframe=true&height=400&width=600', true, '', true);
	else
	parent.TB_show2('', 'redeem_pop.php?tran_id={/literal}{$trans_id}{literal}&TB_iframe=true&height=400&width=600', true, '', true);	
}

//glitter min file.

(function($){$.gritter={};$.gritter.options={position:'',fade_in_speed:'medium',fade_out_speed:1000,time:6000}
$.gritter.add=function(params){try{return Gritter.add(params||{});}catch(e){var err='Gritter Error: '+e;(typeof(console)!='undefined'&&console.error)?console.error(err,params):alert(err);}}
$.gritter.remove=function(id,params){Gritter.removeSpecific(id,params||{});}
$.gritter.removeAll=function(params){Gritter.stop(params||{});}
var Gritter={position:'',fade_in_speed:'',fade_out_speed:'',time:'',_custom_timer:0,_item_count:0,_is_setup:0,_tpl_close:'<div class="gritter-close"></div>',_tpl_item:'<div id="gritter-item-[[number]]" class="gritter-item-wrapper [[item_class]]" style="display:none"><div class="gritter-top"></div><div class="gritter-item">[[image]]<div class="[[class_name]]"><span class="gritter-title">[[username]]</span><p>[[text]]</p></div><div style="clear:both"></div></div><div class="gritter-bottom"></div></div>',_tpl_wrap:'<div id="gritter-notice-wrapper"></div>',add:function(params){if(!params.title||!params.text){throw'You need to fill out the first 2 params: "title" and "text"';}
if(!this._is_setup){this._runSetup();}
var user=params.title,text=params.text,image=params.image||'',sticky=params.sticky||false,item_class=params.class_name||'',position=$.gritter.options.position,time_alive=params.time||'';this._verifyWrapper();this._item_count++;var number=this._item_count,tmp=this._tpl_item;$(['before_open','after_open','before_close','after_close']).each(function(i,val){Gritter['_'+val+'_'+number]=($.isFunction(params[val]))?params[val]:function(){}});this._custom_timer=0;if(time_alive){this._custom_timer=time_alive;}
var image_str=(image!='')?'<img src="'+image+'" class="gritter-image" />':'',class_name=(image!='')?'gritter-with-image':'gritter-without-image';tmp=this._str_replace(['[[username]]','[[text]]','[[image]]','[[number]]','[[class_name]]','[[item_class]]'],[user,text,image_str,this._item_count,class_name,item_class],tmp);this['_before_open_'+number]();$('#gritter-notice-wrapper').addClass(position).append(tmp);var item=$('#gritter-item-'+this._item_count);item.fadeIn(this.fade_in_speed,function(){Gritter['_after_open_'+number]($(this));});if(!sticky){this._setFadeTimer(item,number);}
$(item).bind('mouseenter mouseleave',function(event){if(event.type=='mouseenter'){if(!sticky){Gritter._restoreItemIfFading($(this),number);}}
else{if(!sticky){Gritter._setFadeTimer($(this),number);}}
Gritter._hoverState($(this),event.type);});return number;},_countRemoveWrapper:function(unique_id,e,manual_close){e.remove();this['_after_close_'+unique_id](e,manual_close);if($('.gritter-item-wrapper').length==0){$('#gritter-notice-wrapper').remove();}},_fade:function(e,unique_id,params,unbind_events){var params=params||{},fade=(typeof(params.fade)!='undefined')?params.fade:true;fade_out_speed=params.speed||this.fade_out_speed,manual_close=unbind_events;this['_before_close_'+unique_id](e,manual_close);if(unbind_events){e.unbind('mouseenter mouseleave');}
if(fade){e.animate({opacity:0},fade_out_speed,function(){e.animate({height:0},300,function(){Gritter._countRemoveWrapper(unique_id,e,manual_close);})})}
else{this._countRemoveWrapper(unique_id,e);}},_hoverState:function(e,type){if(type=='mouseenter'){e.addClass('hover');var find_img=e.find('img');(find_img.length)?find_img.before(this._tpl_close):e.find('span').before(this._tpl_close);e.find('.gritter-close').click(function(){var unique_id=e.attr('id').split('-')[2];Gritter.removeSpecific(unique_id,{},e,true);});}
else{e.removeClass('hover');e.find('.gritter-close').remove();}},removeSpecific:function(unique_id,params,e,unbind_events){if(!e){var e=$('#gritter-item-'+unique_id);}
this._fade(e,unique_id,params||{},unbind_events);},_restoreItemIfFading:function(e,unique_id){clearTimeout(this['_int_id_'+unique_id]);e.stop().css({opacity:''});},_runSetup:function(){for(opt in $.gritter.options){this[opt]=$.gritter.options[opt];}
this._is_setup=1;},_setFadeTimer:function(e,unique_id){var timer_str=(this._custom_timer)?this._custom_timer:this.time;this['_int_id_'+unique_id]=setTimeout(function(){Gritter._fade(e,unique_id);},timer_str);},stop:function(params){var before_close=($.isFunction(params.before_close))?params.before_close:function(){};var after_close=($.isFunction(params.after_close))?params.after_close:function(){};var wrap=$('#gritter-notice-wrapper');before_close(wrap);wrap.fadeOut(function(){$(this).remove();after_close();});},_str_replace:function(search,replace,subject,count){var i=0,j=0,temp='',repl='',sl=0,fl=0,f=[].concat(search),r=[].concat(replace),s=subject,ra=r instanceof Array,sa=s instanceof Array;s=[].concat(s);if(count){this.window[count]=0;}
for(i=0,sl=s.length;i<sl;i++){if(s[i]===''){continue;}
for(j=0,fl=f.length;j<fl;j++){temp=s[i]+'';repl=ra?(r[j]!==undefined?r[j]:''):r[0];s[i]=(temp).split(f[j]).join(repl);if(count&&s[i]!==temp){this.window[count]+=(temp.length-s[i].length)/f[j].length;}}}
return sa?s:s[0];},_verifyWrapper:function(){if($('#gritter-notice-wrapper').length==0){$('body').append(this._tpl_wrap);}}}})(jQuery);


// gritter alert file
    function show_gritter_alert_add(name, type){
	// Gritter alert
    if(type == 1)
    {
        var type_text = "Queue";
		var title_text="Added To Queue"	
    }else{
        var type_text = "Favorites";
		var title_text="Favorite Added"
    }
	
	$j.gritter.add({
		title: title_text,
		text: name + ' was added to your '+type_text,
		image: '../images/ico-grwlr-fav-add.png',
		time: 2500
	});
    }
    
    function show_gritter_alert_remove(name,type){
    	// Gritter alert
        if(type == 1)
        {
            var type_text = "Queue";
			var title_text="Removed From Queue"	
        }else{
            var type_text = "Favorites";
			var title_text="Favorite Removed"	
        }
    	$j.gritter.add({
    		title: title_text,
    		text: name + ' was removed from your '+type_text,
    		image: '../images/ico-grwlr-fav-add.png',
    		time: 2500
    	});
    }
    
	/**
 * jQuery Validation Plugin 1.8.1
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-validation/
 * http://docs.jquery.com/Plugins/Validation
 *
 * Copyright (c) 2006 - 2011 Jörn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
(function(c){c.extend(c.fn,{validate:function(a){if(this.length){var b=c.data(this[0],"validator");if(b)return b;b=new c.validator(a,this[0]);c.data(this[0],"validator",b);if(b.settings.onsubmit){this.find("input, button").filter(".cancel").click(function(){b.cancelSubmit=true});b.settings.submitHandler&&this.find("input, button").filter(":submit").click(function(){b.submitButton=this});this.submit(function(d){function e(){if(b.settings.submitHandler){if(b.submitButton)var f=c("<input type='hidden'/>").attr("name",
b.submitButton.name).val(b.submitButton.value).appendTo(b.currentForm);b.settings.submitHandler.call(b,b.currentForm);b.submitButton&&f.remove();return false}return true}b.settings.debug&&d.preventDefault();if(b.cancelSubmit){b.cancelSubmit=false;return e()}if(b.form()){if(b.pendingRequest){b.formSubmitted=true;return false}return e()}else{b.focusInvalid();return false}})}return b}else a&&a.debug&&window.console&&console.warn("nothing selected, can't validate, returning nothing")},valid:function(){if(c(this[0]).is("form"))return this.validate().form();
else{var a=true,b=c(this[0].form).validate();this.each(function(){a&=b.element(this)});return a}},removeAttrs:function(a){var b={},d=this;c.each(a.split(/\s/),function(e,f){b[f]=d.attr(f);d.removeAttr(f)});return b},rules:function(a,b){var d=this[0];if(a){var e=c.data(d.form,"validator").settings,f=e.rules,g=c.validator.staticRules(d);switch(a){case "add":c.extend(g,c.validator.normalizeRule(b));f[d.name]=g;if(b.messages)e.messages[d.name]=c.extend(e.messages[d.name],b.messages);break;case "remove":if(!b){delete f[d.name];
return g}var h={};c.each(b.split(/\s/),function(j,i){h[i]=g[i];delete g[i]});return h}}d=c.validator.normalizeRules(c.extend({},c.validator.metadataRules(d),c.validator.classRules(d),c.validator.attributeRules(d),c.validator.staticRules(d)),d);if(d.required){e=d.required;delete d.required;d=c.extend({required:e},d)}return d}});c.extend(c.expr[":"],{blank:function(a){return!c.trim(""+a.value)},filled:function(a){return!!c.trim(""+a.value)},unchecked:function(a){return!a.checked}});c.validator=function(a,
b){this.settings=c.extend(true,{},c.validator.defaults,a);this.currentForm=b;this.init()};c.validator.format=function(a,b){if(arguments.length==1)return function(){var d=c.makeArray(arguments);d.unshift(a);return c.validator.format.apply(this,d)};if(arguments.length>2&&b.constructor!=Array)b=c.makeArray(arguments).slice(1);if(b.constructor!=Array)b=[b];c.each(b,function(d,e){a=a.replace(RegExp("\\{"+d+"\\}","g"),e)});return a};c.extend(c.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",
validClass:"valid",errorElement:"label",focusInvalid:true,errorContainer:c([]),errorLabelContainer:c([]),onsubmit:true,ignore:[],ignoreTitle:false,onfocusin:function(a){this.lastActive=a;if(this.settings.focusCleanup&&!this.blockFocusCleanup){this.settings.unhighlight&&this.settings.unhighlight.call(this,a,this.settings.errorClass,this.settings.validClass);this.addWrapper(this.errorsFor(a)).hide()}},onfocusout:function(a){if(!this.checkable(a)&&(a.name in this.submitted||!this.optional(a)))this.element(a)},
onkeyup:function(a){if(a.name in this.submitted||a==this.lastElement)this.element(a)},onclick:function(a){if(a.name in this.submitted)this.element(a);else a.parentNode.name in this.submitted&&this.element(a.parentNode)},highlight:function(a,b,d){a.type==="radio"?this.findByName(a.name).addClass(b).removeClass(d):c(a).addClass(b).removeClass(d)},unhighlight:function(a,b,d){a.type==="radio"?this.findByName(a.name).removeClass(b).addClass(d):c(a).removeClass(b).addClass(d)}},setDefaults:function(a){c.extend(c.validator.defaults,
a)},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",number:"Please enter a valid number.",digits:"Please enter only digits.",creditcard:"Please enter a valid credit card number.",equalTo:"Please enter the same value again.",accept:"Please enter a value with a valid extension.",maxlength:c.validator.format("Please enter no more than {0} characters."),
minlength:c.validator.format("Please enter at least {0} characters."),rangelength:c.validator.format("Please enter a value between {0} and {1} characters long."),range:c.validator.format("Please enter a value between {0} and {1}."),max:c.validator.format("Please enter a value less than or equal to {0}."),min:c.validator.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:false,prototype:{init:function(){function a(e){var f=c.data(this[0].form,"validator");e="on"+e.type.replace(/^validate/,
"");f.settings[e]&&f.settings[e].call(f,this[0])}this.labelContainer=c(this.settings.errorLabelContainer);this.errorContext=this.labelContainer.length&&this.labelContainer||c(this.currentForm);this.containers=c(this.settings.errorContainer).add(this.settings.errorLabelContainer);this.submitted={};this.valueCache={};this.pendingRequest=0;this.pending={};this.invalid={};this.reset();var b=this.groups={};c.each(this.settings.groups,function(e,f){c.each(f.split(/\s/),function(g,h){b[h]=e})});var d=this.settings.rules;
c.each(d,function(e,f){d[e]=c.validator.normalizeRule(f)});c(this.currentForm).validateDelegate(":text, :password, :file, select, textarea","focusin focusout keyup",a).validateDelegate(":radio, :checkbox, select, option","click",a);this.settings.invalidHandler&&c(this.currentForm).bind("invalid-form.validate",this.settings.invalidHandler)},form:function(){this.checkForm();c.extend(this.submitted,this.errorMap);this.invalid=c.extend({},this.errorMap);this.valid()||c(this.currentForm).triggerHandler("invalid-form",
[this]);this.showErrors();return this.valid()},checkForm:function(){this.prepareForm();for(var a=0,b=this.currentElements=this.elements();b[a];a++)this.check(b[a]);return this.valid()},element:function(a){this.lastElement=a=this.clean(a);this.prepareElement(a);this.currentElements=c(a);var b=this.check(a);if(b)delete this.invalid[a.name];else this.invalid[a.name]=true;if(!this.numberOfInvalids())this.toHide=this.toHide.add(this.containers);this.showErrors();return b},showErrors:function(a){if(a){c.extend(this.errorMap,
a);this.errorList=[];for(var b in a)this.errorList.push({message:a[b],element:this.findByName(b)[0]});this.successList=c.grep(this.successList,function(d){return!(d.name in a)})}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors()},resetForm:function(){c.fn.resetForm&&c(this.currentForm).resetForm();this.submitted={};this.prepareForm();this.hideErrors();this.elements().removeClass(this.settings.errorClass)},numberOfInvalids:function(){return this.objectLength(this.invalid)},
objectLength:function(a){var b=0,d;for(d in a)b++;return b},hideErrors:function(){this.addWrapper(this.toHide).hide()},valid:function(){return this.size()==0},size:function(){return this.errorList.length},focusInvalid:function(){if(this.settings.focusInvalid)try{c(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin")}catch(a){}},findLastActive:function(){var a=this.lastActive;return a&&c.grep(this.errorList,function(b){return b.element.name==
a.name}).length==1&&a},elements:function(){var a=this,b={};return c(this.currentForm).find("input, select, textarea").not(":submit, :reset, :image, [disabled]").not(this.settings.ignore).filter(function(){!this.name&&a.settings.debug&&window.console&&console.error("%o has no name assigned",this);if(this.name in b||!a.objectLength(c(this).rules()))return false;return b[this.name]=true})},clean:function(a){return c(a)[0]},errors:function(){return c(this.settings.errorElement+"."+this.settings.errorClass,
this.errorContext)},reset:function(){this.successList=[];this.errorList=[];this.errorMap={};this.toShow=c([]);this.toHide=c([]);this.currentElements=c([])},prepareForm:function(){this.reset();this.toHide=this.errors().add(this.containers)},prepareElement:function(a){this.reset();this.toHide=this.errorsFor(a)},check:function(a){a=this.clean(a);if(this.checkable(a))a=this.findByName(a.name).not(this.settings.ignore)[0];var b=c(a).rules(),d=false,e;for(e in b){var f={method:e,parameters:b[e]};try{var g=
c.validator.methods[e].call(this,a.value.replace(/\r/g,""),a,f.parameters);if(g=="dependency-mismatch")d=true;else{d=false;if(g=="pending"){this.toHide=this.toHide.not(this.errorsFor(a));return}if(!g){this.formatAndAdd(a,f);return false}}}catch(h){this.settings.debug&&window.console&&console.log("exception occured when checking element "+a.id+", check the '"+f.method+"' method",h);throw h;}}if(!d){this.objectLength(b)&&this.successList.push(a);return true}},customMetaMessage:function(a,b){if(c.metadata){var d=
this.settings.meta?c(a).metadata()[this.settings.meta]:c(a).metadata();return d&&d.messages&&d.messages[b]}},customMessage:function(a,b){var d=this.settings.messages[a];return d&&(d.constructor==String?d:d[b])},findDefined:function(){for(var a=0;a<arguments.length;a++)if(arguments[a]!==undefined)return arguments[a]},defaultMessage:function(a,b){return this.findDefined(this.customMessage(a.name,b),this.customMetaMessage(a,b),!this.settings.ignoreTitle&&a.title||undefined,c.validator.messages[b],"<strong>Warning: No message defined for "+
a.name+"</strong>")},formatAndAdd:function(a,b){var d=this.defaultMessage(a,b.method),e=/\$?\{(\d+)\}/g;if(typeof d=="function")d=d.call(this,b.parameters,a);else if(e.test(d))d=jQuery.format(d.replace(e,"{$1}"),b.parameters);this.errorList.push({message:d,element:a});this.errorMap[a.name]=d;this.submitted[a.name]=d},addWrapper:function(a){if(this.settings.wrapper)a=a.add(a.parent(this.settings.wrapper));return a},defaultShowErrors:function(){for(var a=0;this.errorList[a];a++){var b=this.errorList[a];
this.settings.highlight&&this.settings.highlight.call(this,b.element,this.settings.errorClass,this.settings.validClass);this.showLabel(b.element,b.message)}if(this.errorList.length)this.toShow=this.toShow.add(this.containers);if(this.settings.success)for(a=0;this.successList[a];a++)this.showLabel(this.successList[a]);if(this.settings.unhighlight){a=0;for(b=this.validElements();b[a];a++)this.settings.unhighlight.call(this,b[a],this.settings.errorClass,this.settings.validClass)}this.toHide=this.toHide.not(this.toShow);
this.hideErrors();this.addWrapper(this.toShow).show()},validElements:function(){return this.currentElements.not(this.invalidElements())},invalidElements:function(){return c(this.errorList).map(function(){return this.element})},showLabel:function(a,b){var d=this.errorsFor(a);if(d.length){d.removeClass().addClass(this.settings.errorClass);d.attr("generated")&&d.html(b)}else{d=c("<"+this.settings.errorElement+"/>").attr({"for":this.idOrName(a),generated:true}).addClass(this.settings.errorClass).html(b||
"");if(this.settings.wrapper)d=d.hide().show().wrap("<"+this.settings.wrapper+"/>").parent();this.labelContainer.append(d).length||(this.settings.errorPlacement?this.settings.errorPlacement(d,c(a)):d.insertAfter(a))}if(!b&&this.settings.success){d.text("");typeof this.settings.success=="string"?d.addClass(this.settings.success):this.settings.success(d)}this.toShow=this.toShow.add(d)},errorsFor:function(a){var b=this.idOrName(a);return this.errors().filter(function(){return c(this).attr("for")==b})},
idOrName:function(a){return this.groups[a.name]||(this.checkable(a)?a.name:a.id||a.name)},checkable:function(a){return/radio|checkbox/i.test(a.type)},findByName:function(a){var b=this.currentForm;return c(document.getElementsByName(a)).map(function(d,e){return e.form==b&&e.name==a&&e||null})},getLength:function(a,b){switch(b.nodeName.toLowerCase()){case "select":return c("option:selected",b).length;case "input":if(this.checkable(b))return this.findByName(b.name).filter(":checked").length}return a.length},
depend:function(a,b){return this.dependTypes[typeof a]?this.dependTypes[typeof a](a,b):true},dependTypes:{"boolean":function(a){return a},string:function(a,b){return!!c(a,b.form).length},"function":function(a,b){return a(b)}},optional:function(a){return!c.validator.methods.required.call(this,c.trim(a.value),a)&&"dependency-mismatch"},startRequest:function(a){if(!this.pending[a.name]){this.pendingRequest++;this.pending[a.name]=true}},stopRequest:function(a,b){this.pendingRequest--;if(this.pendingRequest<
0)this.pendingRequest=0;delete this.pending[a.name];if(b&&this.pendingRequest==0&&this.formSubmitted&&this.form()){c(this.currentForm).submit();this.formSubmitted=false}else if(!b&&this.pendingRequest==0&&this.formSubmitted){c(this.currentForm).triggerHandler("invalid-form",[this]);this.formSubmitted=false}},previousValue:function(a){return c.data(a,"previousValue")||c.data(a,"previousValue",{old:null,valid:true,message:this.defaultMessage(a,"remote")})}},classRuleSettings:{required:{required:true},
email:{email:true},url:{url:true},date:{date:true},dateISO:{dateISO:true},dateDE:{dateDE:true},number:{number:true},numberDE:{numberDE:true},digits:{digits:true},creditcard:{creditcard:true}},addClassRules:function(a,b){a.constructor==String?this.classRuleSettings[a]=b:c.extend(this.classRuleSettings,a)},classRules:function(a){var b={};(a=c(a).attr("class"))&&c.each(a.split(" "),function(){this in c.validator.classRuleSettings&&c.extend(b,c.validator.classRuleSettings[this])});return b},attributeRules:function(a){var b=
{};a=c(a);for(var d in c.validator.methods){var e=a.attr(d);if(e)b[d]=e}b.maxlength&&/-1|2147483647|524288/.test(b.maxlength)&&delete b.maxlength;return b},metadataRules:function(a){if(!c.metadata)return{};var b=c.data(a.form,"validator").settings.meta;return b?c(a).metadata()[b]:c(a).metadata()},staticRules:function(a){var b={},d=c.data(a.form,"validator");if(d.settings.rules)b=c.validator.normalizeRule(d.settings.rules[a.name])||{};return b},normalizeRules:function(a,b){c.each(a,function(d,e){if(e===
false)delete a[d];else if(e.param||e.depends){var f=true;switch(typeof e.depends){case "string":f=!!c(e.depends,b.form).length;break;case "function":f=e.depends.call(b,b)}if(f)a[d]=e.param!==undefined?e.param:true;else delete a[d]}});c.each(a,function(d,e){a[d]=c.isFunction(e)?e(b):e});c.each(["minlength","maxlength","min","max"],function(){if(a[this])a[this]=Number(a[this])});c.each(["rangelength","range"],function(){if(a[this])a[this]=[Number(a[this][0]),Number(a[this][1])]});if(c.validator.autoCreateRanges){if(a.min&&
a.max){a.range=[a.min,a.max];delete a.min;delete a.max}if(a.minlength&&a.maxlength){a.rangelength=[a.minlength,a.maxlength];delete a.minlength;delete a.maxlength}}a.messages&&delete a.messages;return a},normalizeRule:function(a){if(typeof a=="string"){var b={};c.each(a.split(/\s/),function(){b[this]=true});a=b}return a},addMethod:function(a,b,d){c.validator.methods[a]=b;c.validator.messages[a]=d!=undefined?d:c.validator.messages[a];b.length<3&&c.validator.addClassRules(a,c.validator.normalizeRule(a))},
methods:{required:function(a,b,d){if(!this.depend(d,b))return"dependency-mismatch";switch(b.nodeName.toLowerCase()){case "select":return(a=c(b).val())&&a.length>0;case "input":if(this.checkable(b))return this.getLength(a,b)>0;default:return c.trim(a).length>0}},remote:function(a,b,d){if(this.optional(b))return"dependency-mismatch";var e=this.previousValue(b);this.settings.messages[b.name]||(this.settings.messages[b.name]={});e.originalMessage=this.settings.messages[b.name].remote;this.settings.messages[b.name].remote=
e.message;d=typeof d=="string"&&{url:d}||d;if(this.pending[b.name])return"pending";if(e.old===a)return e.valid;e.old=a;var f=this;this.startRequest(b);var g={};g[b.name]=a;c.ajax(c.extend(true,{url:d,mode:"abort",port:"validate"+b.name,dataType:"json",data:g,success:function(h){f.settings.messages[b.name].remote=e.originalMessage;var j=h===true;if(j){var i=f.formSubmitted;f.prepareElement(b);f.formSubmitted=i;f.successList.push(b);f.showErrors()}else{i={};h=h||f.defaultMessage(b,"remote");i[b.name]=
e.message=c.isFunction(h)?h(a):h;f.showErrors(i)}e.valid=j;f.stopRequest(b,j)}},d));return"pending"},minlength:function(a,b,d){return this.optional(b)||this.getLength(c.trim(a),b)>=d},maxlength:function(a,b,d){return this.optional(b)||this.getLength(c.trim(a),b)<=d},rangelength:function(a,b,d){a=this.getLength(c.trim(a),b);return this.optional(b)||a>=d[0]&&a<=d[1]},min:function(a,b,d){return this.optional(b)||a>=d},max:function(a,b,d){return this.optional(b)||a<=d},range:function(a,b,d){return this.optional(b)||
a>=d[0]&&a<=d[1]},email:function(a,b){return this.optional(b)||/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(a)},
url:function(a,b){return this.optional(b)||/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(a)},
date:function(a,b){return this.optional(b)||!/Invalid|NaN/.test(new Date(a))},dateISO:function(a,b){return this.optional(b)||/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(a)},number:function(a,b){return this.optional(b)||/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(a)},digits:function(a,b){return this.optional(b)||/^\d+$/.test(a)},creditcard:function(a,b){if(this.optional(b))return"dependency-mismatch";if(/[^0-9-]+/.test(a))return false;var d=0,e=0,f=false;a=a.replace(/\D/g,"");for(var g=a.length-1;g>=
0;g--){e=a.charAt(g);e=parseInt(e,10);if(f)if((e*=2)>9)e-=9;d+=e;f=!f}return d%10==0},accept:function(a,b,d){d=typeof d=="string"?d.replace(/,/g,"|"):"png|jpe?g|gif";return this.optional(b)||a.match(RegExp(".("+d+")$","i"))},equalTo:function(a,b,d){d=c(d).unbind(".validate-equalTo").bind("blur.validate-equalTo",function(){c(b).valid()});return a==d.val()}}});c.format=c.validator.format})(jQuery);
(function(c){var a={};if(c.ajaxPrefilter)c.ajaxPrefilter(function(d,e,f){e=d.port;if(d.mode=="abort"){a[e]&&a[e].abort();a[e]=f}});else{var b=c.ajax;c.ajax=function(d){var e=("port"in d?d:c.ajaxSettings).port;if(("mode"in d?d:c.ajaxSettings).mode=="abort"){a[e]&&a[e].abort();return a[e]=b.apply(this,arguments)}return b.apply(this,arguments)}}})(jQuery);
(function(c){!jQuery.event.special.focusin&&!jQuery.event.special.focusout&&document.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(e){e=c.event.fix(e);e.type=b;return c.event.handle.call(this,e)}c.event.special[b]={setup:function(){this.addEventListener(a,d,true)},teardown:function(){this.removeEventListener(a,d,true)},handler:function(e){arguments[0]=c.event.fix(e);arguments[0].type=b;return c.event.handle.apply(this,arguments)}}});c.extend(c.fn,{validateDelegate:function(a,
b,d){return this.bind(b,function(e){var f=c(e.target);if(f.is(a))return d.apply(f,arguments)})}})})(jQuery);


/*
 * SimpleModal 1.4.1 - jQuery Plugin
 * http://www.ericmmartin.com/projects/simplemodal/
 * Copyright (c) 2010 Eric Martin (http://twitter.com/ericmmartin)
 * Dual licensed under the MIT and GPL licenses
 * Revision: $Id: jquery.simplemodal.js 261 2010-11-05 21:16:20Z emartin24 $
 */
(function(d){var k=d.browser.msie&&parseInt(d.browser.version)===6&&typeof window.XMLHttpRequest!=="object",m=d.browser.msie&&parseInt(d.browser.version)===7,l=null,f=[];d.modal=function(a,b){return d.modal.impl.init(a,b)};d.modal.close=function(){d.modal.impl.close()};d.modal.focus=function(a){d.modal.impl.focus(a)};d.modal.setContainerDimensions=function(){d.modal.impl.setContainerDimensions()};d.modal.setPosition=function(){d.modal.impl.setPosition()};d.modal.update=function(a,b){d.modal.impl.update(a,
b)};d.fn.modal=function(a){return d.modal.impl.init(this,a)};d.modal.defaults={appendTo:"body",focus:true,opacity:50,overlayId:"simplemodal-overlay",overlayCss:{},containerId:"simplemodal-container",containerCss:{},dataId:"simplemodal-data",dataCss:{},minHeight:null,minWidth:null,maxHeight:null,maxWidth:null,autoResize:false,autoPosition:true,zIndex:1E3,close:true,closeHTML:'<a class="modalCloseImg" title="Close"></a>',closeClass:"simplemodal-close",escClose:true,overlayClose:false,position:null,
persist:false,modal:true,onOpen:null,onShow:null,onClose:null};d.modal.impl={d:{},init:function(a,b){var c=this;if(c.d.data)return false;l=d.browser.msie&&!d.boxModel;c.o=d.extend({},d.modal.defaults,b);c.zIndex=c.o.zIndex;c.occb=false;if(typeof a==="object"){a=a instanceof jQuery?a:d(a);c.d.placeholder=false;if(a.parent().parent().size()>0){a.before(d("<span></span>").attr("id","simplemodal-placeholder").css({display:"none"}));c.d.placeholder=true;c.display=a.css("display");if(!c.o.persist)c.d.orig=
a.clone(true)}}else if(typeof a==="string"||typeof a==="number")a=d("<div></div>").html(a);else{alert("SimpleModal Error: Unsupported data type: "+typeof a);return c}c.create(a);c.open();d.isFunction(c.o.onShow)&&c.o.onShow.apply(c,[c.d]);return c},create:function(a){var b=this;f=b.getDimensions();if(b.o.modal&&k)b.d.iframe=d('<iframe src="javascript:false;"></iframe>').css(d.extend(b.o.iframeCss,{display:"none",opacity:0,position:"fixed",height:f[0],width:f[1],zIndex:b.o.zIndex,top:0,left:0})).appendTo(b.o.appendTo);
b.d.overlay=d("<div></div>").attr("id",b.o.overlayId).addClass("simplemodal-overlay").css(d.extend(b.o.overlayCss,{display:"none",opacity:b.o.opacity/100,height:b.o.modal?f[0]:0,width:b.o.modal?f[1]:0,position:"fixed",left:0,top:0,zIndex:b.o.zIndex+1})).appendTo(b.o.appendTo);b.d.container=d("<div></div>").attr("id",b.o.containerId).addClass("simplemodal-container").css(d.extend(b.o.containerCss,{display:"none",position:"fixed",zIndex:b.o.zIndex+2})).append(b.o.close&&b.o.closeHTML?d(b.o.closeHTML).addClass(b.o.closeClass):
"").appendTo(b.o.appendTo);b.d.wrap=d("<div></div>").attr("tabIndex",-1).addClass("simplemodal-wrap").css({height:"100%",outline:0,width:"100%"}).appendTo(b.d.container);b.d.data=a.attr("id",a.attr("id")||b.o.dataId).addClass("simplemodal-data").css(d.extend(b.o.dataCss,{display:"none"})).appendTo("body");b.setContainerDimensions();b.d.data.appendTo(b.d.wrap);if(k||l)b.fixIE()},bindEvents:function(){var a=this;d("."+a.o.closeClass).bind("click.simplemodal",function(b){b.preventDefault();a.close()});
a.o.modal&&a.o.close&&a.o.overlayClose&&a.d.overlay.bind("click.simplemodal",function(b){b.preventDefault();a.close()});d(document).bind("keydown.simplemodal",function(b){if(a.o.modal&&b.keyCode===9)a.watchTab(b);else if(a.o.close&&a.o.escClose&&b.keyCode===27){b.preventDefault();a.close()}});d(window).bind("resize.simplemodal",function(){f=a.getDimensions();a.o.autoResize?a.setContainerDimensions():a.o.autoPosition&&a.setPosition();if(k||l)a.fixIE();else if(a.o.modal){a.d.iframe&&a.d.iframe.css({height:f[0],
width:f[1]});a.d.overlay.css({height:f[0],width:f[1]})}})},unbindEvents:function(){d("."+this.o.closeClass).unbind("click.simplemodal");d(document).unbind("keydown.simplemodal");d(window).unbind("resize.simplemodal");this.d.overlay.unbind("click.simplemodal")},fixIE:function(){var a=this,b=a.o.position;d.each([a.d.iframe||null,!a.o.modal?null:a.d.overlay,a.d.container],function(c,h){if(h){var g=h[0].style;g.position="absolute";if(c<2){g.removeExpression("height");g.removeExpression("width");g.setExpression("height",
'document.body.scrollHeight > document.body.clientHeight ? document.body.scrollHeight : document.body.clientHeight + "px"');g.setExpression("width",'document.body.scrollWidth > document.body.clientWidth ? document.body.scrollWidth : document.body.clientWidth + "px"')}else{var e;if(b&&b.constructor===Array){c=b[0]?typeof b[0]==="number"?b[0].toString():b[0].replace(/px/,""):h.css("top").replace(/px/,"");c=c.indexOf("%")===-1?c+' + (t = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"':
parseInt(c.replace(/%/,""))+' * ((document.documentElement.clientHeight || document.body.clientHeight) / 100) + (t = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"';if(b[1]){e=typeof b[1]==="number"?b[1].toString():b[1].replace(/px/,"");e=e.indexOf("%")===-1?e+' + (t = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft) + "px"':parseInt(e.replace(/%/,""))+' * ((document.documentElement.clientWidth || document.body.clientWidth) / 100) + (t = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft) + "px"'}}else{c=
'(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (t = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"';e='(document.documentElement.clientWidth || document.body.clientWidth) / 2 - (this.offsetWidth / 2) + (t = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft) + "px"'}g.removeExpression("top");g.removeExpression("left");g.setExpression("top",
c);g.setExpression("left",e)}}})},focus:function(a){var b=this;a=a&&d.inArray(a,["first","last"])!==-1?a:"first";var c=d(":input:enabled:visible:"+a,b.d.wrap);setTimeout(function(){c.length>0?c.focus():b.d.wrap.focus()},10)},getDimensions:function(){var a=d(window);return[d.browser.opera&&d.browser.version>"9.5"&&d.fn.jquery<"1.3"||d.browser.opera&&d.browser.version<"9.5"&&d.fn.jquery>"1.2.6"?a[0].innerHeight:a.height(),a.width()]},getVal:function(a,b){return a?typeof a==="number"?a:a==="auto"?0:
a.indexOf("%")>0?parseInt(a.replace(/%/,""))/100*(b==="h"?f[0]:f[1]):parseInt(a.replace(/px/,"")):null},update:function(a,b){var c=this;if(!c.d.data)return false;c.d.origHeight=c.getVal(a,"h");c.d.origWidth=c.getVal(b,"w");c.d.data.hide();a&&c.d.container.css("height",a);b&&c.d.container.css("width",b);c.setContainerDimensions();c.d.data.show();c.o.focus&&c.focus();c.unbindEvents();c.bindEvents()},setContainerDimensions:function(){var a=this,b=k||m,c=a.d.origHeight?a.d.origHeight:d.browser.opera?
a.d.container.height():a.getVal(b?a.d.container[0].currentStyle.height:a.d.container.css("height"),"h");b=a.d.origWidth?a.d.origWidth:d.browser.opera?a.d.container.width():a.getVal(b?a.d.container[0].currentStyle.width:a.d.container.css("width"),"w");var h=a.d.data.outerHeight(true),g=a.d.data.outerWidth(true);a.d.origHeight=a.d.origHeight||c;a.d.origWidth=a.d.origWidth||b;var e=a.o.maxHeight?a.getVal(a.o.maxHeight,"h"):null,i=a.o.maxWidth?a.getVal(a.o.maxWidth,"w"):null;e=e&&e<f[0]?e:f[0];i=i&&i<
f[1]?i:f[1];var j=a.o.minHeight?a.getVal(a.o.minHeight,"h"):"auto";c=c?a.o.autoResize&&c>e?e:c<j?j:c:h?h>e?e:a.o.minHeight&&j!=="auto"&&h<j?j:h:j;e=a.o.minWidth?a.getVal(a.o.minWidth,"w"):"auto";b=b?a.o.autoResize&&b>i?i:b<e?e:b:g?g>i?i:a.o.minWidth&&e!=="auto"&&g<e?e:g:e;a.d.container.css({height:c,width:b});a.d.wrap.css({overflow:h>c||g>b?"auto":"visible"});a.o.autoPosition&&a.setPosition()},setPosition:function(){var a=this,b,c;b=f[0]/2-a.d.container.outerHeight(true)/2;c=f[1]/2-a.d.container.outerWidth(true)/
2;if(a.o.position&&Object.prototype.toString.call(a.o.position)==="[object Array]"){b=a.o.position[0]||b;c=a.o.position[1]||c}else{b=b;c=c}a.d.container.css({left:c,top:b})},watchTab:function(a){var b=this;if(d(a.target).parents(".simplemodal-container").length>0){b.inputs=d(":input:enabled:visible:first, :input:enabled:visible:last",b.d.data[0]);if(!a.shiftKey&&a.target===b.inputs[b.inputs.length-1]||a.shiftKey&&a.target===b.inputs[0]||b.inputs.length===0){a.preventDefault();b.focus(a.shiftKey?"last":
"first")}}else{a.preventDefault();b.focus()}},open:function(){var a=this;a.d.iframe&&a.d.iframe.show();if(d.isFunction(a.o.onOpen))a.o.onOpen.apply(a,[a.d]);else{a.d.overlay.show();a.d.container.show();a.d.data.show()}a.o.focus&&a.focus();a.bindEvents()},close:function(){var a=this;if(!a.d.data)return false;a.unbindEvents();if(d.isFunction(a.o.onClose)&&!a.occb){a.occb=true;a.o.onClose.apply(a,[a.d])}else{if(a.d.placeholder){var b=d("#simplemodal-placeholder");if(a.o.persist)b.replaceWith(a.d.data.removeClass("simplemodal-data").css("display",
a.display));else{a.d.data.hide().remove();b.replaceWith(a.d.orig)}}else a.d.data.hide().remove();a.d.container.hide().remove();a.d.overlay.hide();a.d.iframe&&a.d.iframe.hide().remove();setTimeout(function(){a.d.overlay.remove();a.d={}},10)}}}})(jQuery);





  /* Tv shows */

// Backwards compatibilty
//var SocialEngineLanguage = SocialEngineAPI.Language;

/* Shadow.js*/
/*
 * Shadowbox.js, version 3.0.3
 * http://shadowbox-js.com/
 *
 * Copyright 2007-2010, Michael J. I. Jackson
 * Date: 2010-07-13 15:21:56 +0000
 */
 var closebox = 0;
(function(window,undefined){var S={version:"3.0.3"};var ua=navigator.userAgent.toLowerCase();if(ua.indexOf("windows")>-1||ua.indexOf("win32")>-1){S.isWindows=true}else{if(ua.indexOf("macintosh")>-1||ua.indexOf("mac os x")>-1){S.isMac=true}else{if(ua.indexOf("linux")>-1){S.isLinux=true}}}S.isIE=ua.indexOf("msie")>-1;S.isIE6=ua.indexOf("msie 6")>-1;S.isIE7=ua.indexOf("msie 7")>-1;S.isGecko=ua.indexOf("gecko")>-1&&ua.indexOf("safari")==-1;S.isWebKit=ua.indexOf("applewebkit/")>-1;var inlineId=/#(.+)$/,galleryName=/^(light|shadow)box\[(.*?)\]/i,inlineParam=/\s*([a-z_]*?)\s*=\s*(.+)\s*/,fileExtension=/[0-9a-z]+$/i,scriptPath=/(.+\/)shadowbox\.js/i;var open=false,initialized=false,lastOptions={},slideDelay=0,slideStart,slideTimer;S.current=-1;S.dimensions=null;S.ease=function(state){return 1+Math.pow(state-1,3)};S.errorInfo={fla:{name:"Flash",url:"http://www.adobe.com/products/flashplayer/"},qt:{name:"QuickTime",url:"http://www.apple.com/quicktime/download/"},wmp:{name:"Windows Media Player",url:"http://www.microsoft.com/windows/windowsmedia/"},f4m:{name:"Flip4Mac",url:"http://www.flip4mac.com/wmv_download.htm"}};S.gallery=[];S.onReady=noop;S.path=null;S.player=null;S.playerId="sb-player";S.options={animate:true,animateFade:true,autoplayMovies:true,continuous:false,enableKeys:true,flashParams:{bgcolor:"#000000",allowfullscreen:true},flashVars:{},flashVersion:"9.0.115",handleOversize:"resize",handleUnsupported:"link",onChange:noop,onClose:noop,onFinish:noop,onOpen:noop,showMovieControls:true,skipSetup:false,slideshowDelay:0,viewportPadding:20};S.getCurrent=function(){return S.current>-1?S.gallery[S.current]:null};S.hasNext=function(){return S.gallery.length>1&&(S.current!=S.gallery.length-1||S.options.continuous)};S.isOpen=function(){return open};S.isPaused=function(){return slideTimer=="pause"};S.applyOptions=function(options){lastOptions=apply({},S.options);apply(S.options,options)};S.revertOptions=function(){apply(S.options,lastOptions)};S.init=function(options,callback){if(initialized){return}initialized=true;if(S.skin.options){apply(S.options,S.skin.options)}if(options){apply(S.options,options)}if(!S.path){var path,scripts=document.getElementsByTagName("script");for(var i=0,len=scripts.length;i<len;++i){path=scriptPath.exec(scripts[i].src);if(path){S.path=path[1];break}}}if(callback){S.onReady=callback}bindLoad()};S.open=function(obj){if(open){return}var gc=S.makeGallery(obj);S.gallery=gc[0];S.current=gc[1];obj=S.getCurrent();if(obj==null){return}S.applyOptions(obj.options||{});filterGallery();if(S.gallery.length){obj=S.getCurrent();if(S.options.onOpen(obj)===false){return}open=true;S.skin.onOpen(obj,load)}};S.close=function(){closebox = 1;if(!open){return}open=false;if(S.player){S.player.remove();S.player=null}if(typeof slideTimer=="number"){clearTimeout(slideTimer);slideTimer=null}slideDelay=0;listenKeys(false);S.options.onClose(S.getCurrent());S.skin.onClose();S.revertOptions()};S.play=function(){if(!S.hasNext()){return}if(!slideDelay){slideDelay=S.options.slideshowDelay*1000}if(slideDelay){slideStart=now();slideTimer=setTimeout(function(){slideDelay=slideStart=0;S.next()},slideDelay);if(S.skin.onPlay){S.skin.onPlay()}}};S.pause=function(){if(typeof slideTimer!="number"){return}slideDelay=Math.max(0,slideDelay-(now()-slideStart));if(slideDelay){clearTimeout(slideTimer);slideTimer="pause";if(S.skin.onPause){S.skin.onPause()}}};S.change=function(index){if(!(index in S.gallery)){if(S.options.continuous){index=(index<0?S.gallery.length+index:0);if(!(index in S.gallery)){return}}else{return}}S.current=index;if(typeof slideTimer=="number"){clearTimeout(slideTimer);slideTimer=null;slideDelay=slideStart=0}S.options.onChange(S.getCurrent());load(true)};S.next=function(){S.change(S.current+1)};S.previous=function(){S.change(S.current-1)};S.setDimensions=function(height,width,maxHeight,maxWidth,topBottom,leftRight,padding,preserveAspect){var originalHeight=height,originalWidth=width;var extraHeight=2*padding+topBottom;if(height+extraHeight>maxHeight){height=maxHeight-extraHeight}var extraWidth=2*padding+leftRight;if(width+extraWidth>maxWidth){width=maxWidth-extraWidth}var changeHeight=(originalHeight-height)/originalHeight,changeWidth=(originalWidth-width)/originalWidth,oversized=(changeHeight>0||changeWidth>0);if(preserveAspect&&oversized){if(changeHeight>changeWidth){width=Math.round((originalWidth/originalHeight)*height)}else{if(changeWidth>changeHeight){height=Math.round((originalHeight/originalWidth)*width)}}}S.dimensions={height:height+topBottom,width:width+leftRight,innerHeight:height,innerWidth:width,top:Math.floor((maxHeight-(height+extraHeight))/2+padding),left:Math.floor((maxWidth-(width+extraWidth))/2+padding),oversized:oversized};return S.dimensions};S.makeGallery=function(obj){var gallery=[],current=-1;if(typeof obj=="string"){obj=[obj]}if(typeof obj.length=="number"){each(obj,function(i,o){if(o.content){gallery[i]=o}else{gallery[i]={content:o}}});current=0}else{if(obj.tagName){var cacheObj=S.getCache(obj);obj=cacheObj?cacheObj:S.makeObject(obj)}if(obj.gallery){gallery=[];var o;for(var key in S.cache){o=S.cache[key];if(o.gallery&&o.gallery==obj.gallery){if(current==-1&&o.content==obj.content){current=gallery.length}gallery.push(o)}}if(current==-1){gallery.unshift(obj);current=0}}else{gallery=[obj];current=0}}each(gallery,function(i,o){gallery[i]=apply({},o)});return[gallery,current]};S.makeObject=function(link,options){var obj={content:link.href,title:link.getAttribute("title")||"",link:link};if(options){options=apply({},options);each(["player","title","height","width","gallery"],function(i,o){if(typeof options[o]!="undefined"){obj[o]=options[o];delete options[o]}});obj.options=options}else{obj.options={}}if(!obj.player){obj.player=S.getPlayer(obj.content)}var rel=link.getAttribute("rel");if(rel){var match=rel.match(galleryName);if(match){obj.gallery=escape(match[2])}each(rel.split(";"),function(i,p){match=p.match(inlineParam);if(match){obj[match[1]]=match[2]}})}return obj};S.getPlayer=function(content){if(content.indexOf("#")>-1&&content.indexOf(document.location.href)==0){return"inline"}var q=content.indexOf("?");if(q>-1){content=content.substring(0,q)}var ext,m=content.match(fileExtension);if(m){ext=m[0].toLowerCase()}if(ext){if(S.img&&S.img.ext.indexOf(ext)>-1){return"img"}if(S.swf&&S.swf.ext.indexOf(ext)>-1){return"swf"}if(S.flv&&S.flv.ext.indexOf(ext)>-1){return"flv"}if(S.qt&&S.qt.ext.indexOf(ext)>-1){if(S.wmp&&S.wmp.ext.indexOf(ext)>-1){return"qtwmp"}else{return"qt"}}if(S.wmp&&S.wmp.ext.indexOf(ext)>-1){return"wmp"}}return"iframe"};function filterGallery(){var err=S.errorInfo,plugins=S.plugins,obj,remove,needed,m,format,replace,inlineEl,flashVersion;for(var i=0;i<S.gallery.length;++i){obj=S.gallery[i];remove=false;needed=null;switch(obj.player){case"flv":case"swf":if(!plugins.fla){needed="fla"}break;case"qt":if(!plugins.qt){needed="qt"}break;case"wmp":if(S.isMac){if(plugins.qt&&plugins.f4m){obj.player="qt"}else{needed="qtf4m"}}else{if(!plugins.wmp){needed="wmp"}}break;case"qtwmp":if(plugins.qt){obj.player="qt"}else{if(plugins.wmp){obj.player="wmp"}else{needed="qtwmp"}}break}if(needed){if(S.options.handleUnsupported=="link"){switch(needed){case"qtf4m":format="shared";replace=[err.qt.url,err.qt.name,err.f4m.url,err.f4m.name];break;case"qtwmp":format="either";replace=[err.qt.url,err.qt.name,err.wmp.url,err.wmp.name];break;default:format="single";replace=[err[needed].url,err[needed].name]}obj.player="html";obj.content='<div class="sb-message">'+sprintf(S.lang.errors[format],replace)+"</div>"}else{remove=true}}else{if(obj.player=="inline"){m=inlineId.exec(obj.content);if(m){inlineEl=get(m[1]);if(inlineEl){obj.content=inlineEl.innerHTML}else{remove=true}}else{remove=true}}else{if(obj.player=="swf"||obj.player=="flv"){flashVersion=(obj.options&&obj.options.flashVersion)||S.options.flashVersion;if(S.flash&&!S.flash.hasFlashPlayerVersion(flashVersion)){obj.width=310;obj.height=177}}}}if(remove){S.gallery.splice(i,1);if(i<S.current){--S.current}else{if(i==S.current){S.current=i>0?i-1:i}}--i}}}function listenKeys(on){if(!S.options.enableKeys){return}(on?addEvent:removeEvent)(document,"keydown",handleKey)}function handleKey(e){if(e.metaKey||e.shiftKey||e.altKey||e.ctrlKey){return}var code=keyCode(e),handler;switch(code){case 81:case 88:case 27:handler=S.close;break;case 37:handler=S.previous;break;case 39:handler=S.next;break;case 32:handler=typeof slideTimer=="number"?S.pause:S.play;break}if(handler){preventDefault(e);handler()}}function load(changing){listenKeys(false);var obj=S.getCurrent();var player=(obj.player=="inline"?"html":obj.player);if(typeof S[player]!="function"){throw"unknown player "+player}if(changing){S.player.remove();S.revertOptions();S.applyOptions(obj.options||{})}S.player=new S[player](obj,S.playerId);if(S.gallery.length>1){var next=S.gallery[S.current+1]||S.gallery[0];if(next.player=="img"){var a=new Image();a.src=next.content}var prev=S.gallery[S.current-1]||S.gallery[S.gallery.length-1];if(prev.player=="img"){var b=new Image();b.src=prev.content}}S.skin.onLoad(changing,waitReady)}function waitReady(){if(!open){return}if(typeof S.player.ready!="undefined"){var timer=setInterval(function(){if(open){if(S.player.ready){clearInterval(timer);timer=null;S.skin.onReady(show)}}else{clearInterval(timer);timer=null}},10)}else{S.skin.onReady(show)}}function show(){if(!open){return}S.player.append(S.skin.body,S.dimensions);S.skin.onShow(finish)}function finish(){if(!open){return}if(S.player.onLoad){S.player.onLoad()}S.options.onFinish(S.getCurrent());if(!S.isPaused()){S.play()}listenKeys(true)}if(!Array.prototype.indexOf){Array.prototype.indexOf=function(obj,from){var len=this.length>>>0;from=from||0;if(from<0){from+=len}for(;from<len;++from){if(from in this&&this[from]===obj){return from}}return -1}}function now(){return(new Date).getTime()}function apply(original,extension){for(var property in extension){original[property]=extension[property]}return original}function each(obj,callback){var i=0,len=obj.length;for(var value=obj[0];i<len&&callback.call(value,i,value)!==false;value=obj[++i]){}}function sprintf(str,replace){return str.replace(/\{(\w+?)\}/g,function(match,i){return replace[i]})}function noop(){}function get(id){return document.getElementById(id)}function remove(el){el.parentNode.removeChild(el)}var supportsOpacity=true,supportsFixed=true;function checkSupport(){var body=document.body,div=document.createElement("div");supportsOpacity=typeof div.style.opacity==="string";div.style.position="fixed";div.style.margin=0;div.style.top="20px";body.appendChild(div,body.firstChild);supportsFixed=div.offsetTop==20;body.removeChild(div)}S.getStyle=(function(){var opacity=/opacity=([^)]*)/,getComputedStyle=document.defaultView&&document.defaultView.getComputedStyle;return function(el,style){var ret;if(!supportsOpacity&&style=="opacity"&&el.currentStyle){ret=opacity.test(el.currentStyle.filter||"")?(parseFloat(RegExp.$1)/100)+"":"";return ret===""?"1":ret}if(getComputedStyle){var computedStyle=getComputedStyle(el,null);if(computedStyle){ret=computedStyle[style]}if(style=="opacity"&&ret==""){ret="1"}}else{ret=el.currentStyle[style]}return ret}})();S.appendHTML=function(el,html){if(el.insertAdjacentHTML){el.insertAdjacentHTML("BeforeEnd",html)}else{if(el.lastChild){var range=el.ownerDocument.createRange();range.setStartAfter(el.lastChild);var frag=range.createContextualFragment(html);el.appendChild(frag)}else{el.innerHTML=html}}};S.getWindowSize=function(dimension){if(document.compatMode==="CSS1Compat"){return document.documentElement["client"+dimension]}return document.body["client"+dimension]};S.setOpacity=function(el,opacity){var style=el.style;if(supportsOpacity){style.opacity=(opacity==1?"":opacity)}else{style.zoom=1;if(opacity==1){if(typeof style.filter=="string"&&(/alpha/i).test(style.filter)){style.filter=style.filter.replace(/\s*[\w\.]*alpha\([^\)]*\);?/gi,"")}}else{style.filter=(style.filter||"").replace(/\s*[\w\.]*alpha\([^\)]*\)/gi,"")+" alpha(opacity="+(opacity*100)+")"}}};S.clearOpacity=function(el){S.setOpacity(el,1)};function getTarget(e){var target=e.target?e.target:e.srcElement;return target.nodeType==3?target.parentNode:target}function getPageXY(e){var x=e.pageX||(e.clientX+(document.documentElement.scrollLeft||document.body.scrollLeft)),y=e.pageY||(e.clientY+(document.documentElement.scrollTop||document.body.scrollTop));return[x,y]}function preventDefault(e){e.preventDefault()}function keyCode(e){return e.which?e.which:e.keyCode}function addEvent(el,type,handler){if(el.addEventListener){el.addEventListener(type,handler,false)}else{if(el.nodeType===3||el.nodeType===8){return}if(el.setInterval&&(el!==window&&!el.frameElement)){el=window}if(!handler.__guid){handler.__guid=addEvent.guid++}if(!el.events){el.events={}}var handlers=el.events[type];if(!handlers){handlers=el.events[type]={};if(el["on"+type]){handlers[0]=el["on"+type]}}handlers[handler.__guid]=handler;el["on"+type]=addEvent.handleEvent}}addEvent.guid=1;addEvent.handleEvent=function(event){var result=true;event=event||addEvent.fixEvent(((this.ownerDocument||this.document||this).parentWindow||window).event);var handlers=this.events[event.type];for(var i in handlers){this.__handleEvent=handlers[i];if(this.__handleEvent(event)===false){result=false}}return result};addEvent.preventDefault=function(){this.returnValue=false};addEvent.stopPropagation=function(){this.cancelBubble=true};addEvent.fixEvent=function(e){e.preventDefault=addEvent.preventDefault;e.stopPropagation=addEvent.stopPropagation;return e};function removeEvent(el,type,handler){if(el.removeEventListener){el.removeEventListener(type,handler,false)}else{if(el.events&&el.events[type]){delete el.events[type][handler.__guid]}}}var loaded=false,DOMContentLoaded;if(document.addEventListener){DOMContentLoaded=function(){document.removeEventListener("DOMContentLoaded",DOMContentLoaded,false);S.load()}}else{if(document.attachEvent){DOMContentLoaded=function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",DOMContentLoaded);S.load()}}}}function doScrollCheck(){if(loaded){return}try{document.documentElement.doScroll("left")}catch(e){setTimeout(doScrollCheck,1);return}S.load()}function bindLoad(){if(document.readyState==="complete"){return S.load()}if(document.addEventListener){document.addEventListener("DOMContentLoaded",DOMContentLoaded,false);window.addEventListener("load",S.load,false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",DOMContentLoaded);window.attachEvent("onload",S.load);var topLevel=false;try{topLevel=window.frameElement===null}catch(e){}if(document.documentElement.doScroll&&topLevel){doScrollCheck()}}}}S.load=function(){if(loaded){return}if(!document.body){return setTimeout(S.load,13)}loaded=true;checkSupport();S.onReady();if(!S.options.skipSetup){S.setup()}S.skin.init()};S.plugins={};if(navigator.plugins&&navigator.plugins.length){var names=[];each(navigator.plugins,function(i,p){names.push(p.name)});names=names.join(",");var f4m=names.indexOf("Flip4Mac")>-1;S.plugins={fla:names.indexOf("Shockwave Flash")>-1,qt:names.indexOf("QuickTime")>-1,wmp:!f4m&&names.indexOf("Windows Media")>-1,f4m:f4m}}else{var detectPlugin=function(name){var axo;try{axo=new ActiveXObject(name)}catch(e){}return !!axo};S.plugins={fla:detectPlugin("ShockwaveFlash.ShockwaveFlash"),qt:detectPlugin("QuickTime.QuickTime"),wmp:detectPlugin("wmplayer.ocx"),f4m:false}}var relAttr=/^(light|shadow)box/i,expando="shadowboxCacheKey",cacheKey=1;S.cache={};S.select=function(selector){var links=[];if(!selector){var rel;each(document.getElementsByTagName("a"),function(i,el){rel=el.getAttribute("rel");if(rel&&relAttr.test(rel)){links.push(el)}})}else{var length=selector.length;if(length){if(typeof selector=="string"){if(S.find){links=S.find(selector)}}else{if(length==2&&typeof selector[0]=="string"&&selector[1].nodeType){if(S.find){links=S.find(selector[0],selector[1])}}else{for(var i=0;i<length;++i){links[i]=selector[i]}}}}else{links.push(selector)}}return links};S.setup=function(selector,options){each(S.select(selector),function(i,link){S.addCache(link,options)})};S.teardown=function(selector){each(S.select(selector),function(i,link){S.removeCache(link)})};S.addCache=function(link,options){var key=link[expando];if(key==undefined){key=cacheKey++;link[expando]=key;addEvent(link,"click",handleClick)}S.cache[key]=S.makeObject(link,options)};S.removeCache=function(link){removeEvent(link,"click",handleClick);delete S.cache[link[expando]];link[expando]=null};S.getCache=function(link){var key=link[expando];return(key in S.cache&&S.cache[key])};S.clearCache=function(){for(var key in S.cache){S.removeCache(S.cache[key].link)}S.cache={}};function handleClick(e){S.open(this);if(S.gallery.length){preventDefault(e)}}
/*
 * Sizzle CSS Selector Engine - v1.0
 *  Copyright 2009, The Dojo Foundation
 *  Released under the MIT, BSD, and GPL Licenses.
 *  More information: http://sizzlejs.com/
 *
 * Modified for inclusion in Shadowbox.js
 */
S.find=(function(){var chunker=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,done=0,toString=Object.prototype.toString,hasDuplicate=false,baseHasDuplicate=true;[0,0].sort(function(){baseHasDuplicate=false;return 0});var Sizzle=function(selector,context,results,seed){results=results||[];var origContext=context=context||document;if(context.nodeType!==1&&context.nodeType!==9){return[]}if(!selector||typeof selector!=="string"){return results}var parts=[],m,set,checkSet,extra,prune=true,contextXML=isXML(context),soFar=selector;while((chunker.exec(""),m=chunker.exec(soFar))!==null){soFar=m[3];parts.push(m[1]);if(m[2]){extra=m[3];break}}if(parts.length>1&&origPOS.exec(selector)){if(parts.length===2&&Expr.relative[parts[0]]){set=posProcess(parts[0]+parts[1],context)}else{set=Expr.relative[parts[0]]?[context]:Sizzle(parts.shift(),context);while(parts.length){selector=parts.shift();if(Expr.relative[selector]){selector+=parts.shift()}set=posProcess(selector,set)}}}else{if(!seed&&parts.length>1&&context.nodeType===9&&!contextXML&&Expr.match.ID.test(parts[0])&&!Expr.match.ID.test(parts[parts.length-1])){var ret=Sizzle.find(parts.shift(),context,contextXML);context=ret.expr?Sizzle.filter(ret.expr,ret.set)[0]:ret.set[0]}if(context){var ret=seed?{expr:parts.pop(),set:makeArray(seed)}:Sizzle.find(parts.pop(),parts.length===1&&(parts[0]==="~"||parts[0]==="+")&&context.parentNode?context.parentNode:context,contextXML);set=ret.expr?Sizzle.filter(ret.expr,ret.set):ret.set;if(parts.length>0){checkSet=makeArray(set)}else{prune=false}while(parts.length){var cur=parts.pop(),pop=cur;if(!Expr.relative[cur]){cur=""}else{pop=parts.pop()}if(pop==null){pop=context}Expr.relative[cur](checkSet,pop,contextXML)}}else{checkSet=parts=[]}}if(!checkSet){checkSet=set}if(!checkSet){throw"Syntax error, unrecognized expression: "+(cur||selector)}if(toString.call(checkSet)==="[object Array]"){if(!prune){results.push.apply(results,checkSet)}else{if(context&&context.nodeType===1){for(var i=0;checkSet[i]!=null;i++){if(checkSet[i]&&(checkSet[i]===true||checkSet[i].nodeType===1&&contains(context,checkSet[i]))){results.push(set[i])}}}else{for(var i=0;checkSet[i]!=null;i++){if(checkSet[i]&&checkSet[i].nodeType===1){results.push(set[i])}}}}}else{makeArray(checkSet,results)}if(extra){Sizzle(extra,origContext,results,seed);Sizzle.uniqueSort(results)}return results};Sizzle.uniqueSort=function(results){if(sortOrder){hasDuplicate=baseHasDuplicate;results.sort(sortOrder);if(hasDuplicate){for(var i=1;i<results.length;i++){if(results[i]===results[i-1]){results.splice(i--,1)}}}}return results};Sizzle.matches=function(expr,set){return Sizzle(expr,null,null,set)};Sizzle.find=function(expr,context,isXML){var set,match;if(!expr){return[]}for(var i=0,l=Expr.order.length;i<l;i++){var type=Expr.order[i],match;if((match=Expr.leftMatch[type].exec(expr))){var left=match[1];match.splice(1,1);if(left.substr(left.length-1)!=="\\"){match[1]=(match[1]||"").replace(/\\/g,"");set=Expr.find[type](match,context,isXML);if(set!=null){expr=expr.replace(Expr.match[type],"");break}}}}if(!set){set=context.getElementsByTagName("*")}return{set:set,expr:expr}};Sizzle.filter=function(expr,set,inplace,not){var old=expr,result=[],curLoop=set,match,anyFound,isXMLFilter=set&&set[0]&&isXML(set[0]);while(expr&&set.length){for(var type in Expr.filter){if((match=Expr.match[type].exec(expr))!=null){var filter=Expr.filter[type],found,item;anyFound=false;if(curLoop===result){result=[]}if(Expr.preFilter[type]){match=Expr.preFilter[type](match,curLoop,inplace,result,not,isXMLFilter);if(!match){anyFound=found=true}else{if(match===true){continue}}}if(match){for(var i=0;(item=curLoop[i])!=null;i++){if(item){found=filter(item,match,i,curLoop);var pass=not^!!found;if(inplace&&found!=null){if(pass){anyFound=true}else{curLoop[i]=false}}else{if(pass){result.push(item);anyFound=true}}}}}if(found!==undefined){if(!inplace){curLoop=result}expr=expr.replace(Expr.match[type],"");if(!anyFound){return[]}break}}}if(expr===old){if(anyFound==null){throw"Syntax error, unrecognized expression: "+expr}else{break}}old=expr}return curLoop};var Expr=Sizzle.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(elem){return elem.getAttribute("href")}},relative:{"+":function(checkSet,part){var isPartStr=typeof part==="string",isTag=isPartStr&&!/\W/.test(part),isPartStrNotTag=isPartStr&&!isTag;if(isTag){part=part.toLowerCase()}for(var i=0,l=checkSet.length,elem;i<l;i++){if((elem=checkSet[i])){while((elem=elem.previousSibling)&&elem.nodeType!==1){}checkSet[i]=isPartStrNotTag||elem&&elem.nodeName.toLowerCase()===part?elem||false:elem===part}}if(isPartStrNotTag){Sizzle.filter(part,checkSet,true)}},">":function(checkSet,part){var isPartStr=typeof part==="string";if(isPartStr&&!/\W/.test(part)){part=part.toLowerCase();for(var i=0,l=checkSet.length;i<l;i++){var elem=checkSet[i];if(elem){var parent=elem.parentNode;checkSet[i]=parent.nodeName.toLowerCase()===part?parent:false}}}else{for(var i=0,l=checkSet.length;i<l;i++){var elem=checkSet[i];if(elem){checkSet[i]=isPartStr?elem.parentNode:elem.parentNode===part}}if(isPartStr){Sizzle.filter(part,checkSet,true)}}},"":function(checkSet,part,isXML){var doneName=done++,checkFn=dirCheck;if(typeof part==="string"&&!/\W/.test(part)){var nodeCheck=part=part.toLowerCase();checkFn=dirNodeCheck}checkFn("parentNode",part,doneName,checkSet,nodeCheck,isXML)},"~":function(checkSet,part,isXML){var doneName=done++,checkFn=dirCheck;if(typeof part==="string"&&!/\W/.test(part)){var nodeCheck=part=part.toLowerCase();checkFn=dirNodeCheck}checkFn("previousSibling",part,doneName,checkSet,nodeCheck,isXML)}},find:{ID:function(match,context,isXML){if(typeof context.getElementById!=="undefined"&&!isXML){var m=context.getElementById(match[1]);return m?[m]:[]}},NAME:function(match,context){if(typeof context.getElementsByName!=="undefined"){var ret=[],results=context.getElementsByName(match[1]);for(var i=0,l=results.length;i<l;i++){if(results[i].getAttribute("name")===match[1]){ret.push(results[i])}}return ret.length===0?null:ret}},TAG:function(match,context){return context.getElementsByTagName(match[1])}},preFilter:{CLASS:function(match,curLoop,inplace,result,not,isXML){match=" "+match[1].replace(/\\/g,"")+" ";if(isXML){return match}for(var i=0,elem;(elem=curLoop[i])!=null;i++){if(elem){if(not^(elem.className&&(" "+elem.className+" ").replace(/[\t\n]/g," ").indexOf(match)>=0)){if(!inplace){result.push(elem)}}else{if(inplace){curLoop[i]=false}}}}return false},ID:function(match){return match[1].replace(/\\/g,"")},TAG:function(match,curLoop){return match[1].toLowerCase()},CHILD:function(match){if(match[1]==="nth"){var test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(match[2]==="even"&&"2n"||match[2]==="odd"&&"2n+1"||!/\D/.test(match[2])&&"0n+"+match[2]||match[2]);match[2]=(test[1]+(test[2]||1))-0;match[3]=test[3]-0}match[0]=done++;return match},ATTR:function(match,curLoop,inplace,result,not,isXML){var name=match[1].replace(/\\/g,"");if(!isXML&&Expr.attrMap[name]){match[1]=Expr.attrMap[name]}if(match[2]==="~="){match[4]=" "+match[4]+" "}return match},PSEUDO:function(match,curLoop,inplace,result,not){if(match[1]==="not"){if((chunker.exec(match[3])||"").length>1||/^\w/.test(match[3])){match[3]=Sizzle(match[3],null,null,curLoop)}else{var ret=Sizzle.filter(match[3],curLoop,inplace,true^not);if(!inplace){result.push.apply(result,ret)}return false}}else{if(Expr.match.POS.test(match[0])||Expr.match.CHILD.test(match[0])){return true}}return match},POS:function(match){match.unshift(true);return match}},filters:{enabled:function(elem){return elem.disabled===false&&elem.type!=="hidden"},disabled:function(elem){return elem.disabled===true},checked:function(elem){return elem.checked===true},selected:function(elem){elem.parentNode.selectedIndex;return elem.selected===true},parent:function(elem){return !!elem.firstChild},empty:function(elem){return !elem.firstChild},has:function(elem,i,match){return !!Sizzle(match[3],elem).length},header:function(elem){return/h\d/i.test(elem.nodeName)},text:function(elem){return"text"===elem.type},radio:function(elem){return"radio"===elem.type},checkbox:function(elem){return"checkbox"===elem.type},file:function(elem){return"file"===elem.type},password:function(elem){return"password"===elem.type},submit:function(elem){return"submit"===elem.type},image:function(elem){return"image"===elem.type},reset:function(elem){return"reset"===elem.type},button:function(elem){return"button"===elem.type||elem.nodeName.toLowerCase()==="button"},input:function(elem){return/input|select|textarea|button/i.test(elem.nodeName)}},setFilters:{first:function(elem,i){return i===0},last:function(elem,i,match,array){return i===array.length-1},even:function(elem,i){return i%2===0},odd:function(elem,i){return i%2===1},lt:function(elem,i,match){return i<match[3]-0},gt:function(elem,i,match){return i>match[3]-0},nth:function(elem,i,match){return match[3]-0===i},eq:function(elem,i,match){return match[3]-0===i}},filter:{PSEUDO:function(elem,match,i,array){var name=match[1],filter=Expr.filters[name];if(filter){return filter(elem,i,match,array)}else{if(name==="contains"){return(elem.textContent||elem.innerText||getText([elem])||"").indexOf(match[3])>=0}else{if(name==="not"){var not=match[3];for(var i=0,l=not.length;i<l;i++){if(not[i]===elem){return false}}return true}else{throw"Syntax error, unrecognized expression: "+name}}}},CHILD:function(elem,match){var type=match[1],node=elem;switch(type){case"only":case"first":while((node=node.previousSibling)){if(node.nodeType===1){return false}}if(type==="first"){return true}node=elem;case"last":while((node=node.nextSibling)){if(node.nodeType===1){return false}}return true;case"nth":var first=match[2],last=match[3];if(first===1&&last===0){return true}var doneName=match[0],parent=elem.parentNode;if(parent&&(parent.sizcache!==doneName||!elem.nodeIndex)){var count=0;for(node=parent.firstChild;node;node=node.nextSibling){if(node.nodeType===1){node.nodeIndex=++count}}parent.sizcache=doneName}var diff=elem.nodeIndex-last;if(first===0){return diff===0}else{return(diff%first===0&&diff/first>=0)}}},ID:function(elem,match){return elem.nodeType===1&&elem.getAttribute("id")===match},TAG:function(elem,match){return(match==="*"&&elem.nodeType===1)||elem.nodeName.toLowerCase()===match},CLASS:function(elem,match){return(" "+(elem.className||elem.getAttribute("class"))+" ").indexOf(match)>-1},ATTR:function(elem,match){var name=match[1],result=Expr.attrHandle[name]?Expr.attrHandle[name](elem):elem[name]!=null?elem[name]:elem.getAttribute(name),value=result+"",type=match[2],check=match[4];return result==null?type==="!=":type==="="?value===check:type==="*="?value.indexOf(check)>=0:type==="~="?(" "+value+" ").indexOf(check)>=0:!check?value&&result!==false:type==="!="?value!==check:type==="^="?value.indexOf(check)===0:type==="$="?value.substr(value.length-check.length)===check:type==="|="?value===check||value.substr(0,check.length+1)===check+"-":false},POS:function(elem,match,i,array){var name=match[2],filter=Expr.setFilters[name];if(filter){return filter(elem,i,match,array)}}}};var origPOS=Expr.match.POS;for(var type in Expr.match){Expr.match[type]=new RegExp(Expr.match[type].source+/(?![^\[]*\])(?![^\(]*\))/.source);Expr.leftMatch[type]=new RegExp(/(^(?:.|\r|\n)*?)/.source+Expr.match[type].source)}var makeArray=function(array,results){array=Array.prototype.slice.call(array,0);if(results){results.push.apply(results,array);return results}return array};try{Array.prototype.slice.call(document.documentElement.childNodes,0)}catch(e){makeArray=function(array,results){var ret=results||[];if(toString.call(array)==="[object Array]"){Array.prototype.push.apply(ret,array)}else{if(typeof array.length==="number"){for(var i=0,l=array.length;i<l;i++){ret.push(array[i])}}else{for(var i=0;array[i];i++){ret.push(array[i])}}}return ret}}var sortOrder;if(document.documentElement.compareDocumentPosition){sortOrder=function(a,b){if(!a.compareDocumentPosition||!b.compareDocumentPosition){if(a==b){hasDuplicate=true}return a.compareDocumentPosition?-1:1}var ret=a.compareDocumentPosition(b)&4?-1:a===b?0:1;if(ret===0){hasDuplicate=true}return ret}}else{if("sourceIndex" in document.documentElement){sortOrder=function(a,b){if(!a.sourceIndex||!b.sourceIndex){if(a==b){hasDuplicate=true}return a.sourceIndex?-1:1}var ret=a.sourceIndex-b.sourceIndex;if(ret===0){hasDuplicate=true}return ret}}else{if(document.createRange){sortOrder=function(a,b){if(!a.ownerDocument||!b.ownerDocument){if(a==b){hasDuplicate=true}return a.ownerDocument?-1:1}var aRange=a.ownerDocument.createRange(),bRange=b.ownerDocument.createRange();aRange.setStart(a,0);aRange.setEnd(a,0);bRange.setStart(b,0);bRange.setEnd(b,0);var ret=aRange.compareBoundaryPoints(Range.START_TO_END,bRange);if(ret===0){hasDuplicate=true}return ret}}}}function getText(elems){var ret="",elem;for(var i=0;elems[i];i++){elem=elems[i];if(elem.nodeType===3||elem.nodeType===4){ret+=elem.nodeValue}else{if(elem.nodeType!==8){ret+=getText(elem.childNodes)}}}return ret}(function(){var form=document.createElement("div"),id="script"+(new Date).getTime();form.innerHTML="<a name='"+id+"'/>";var root=document.documentElement;root.insertBefore(form,root.firstChild);if(document.getElementById(id)){Expr.find.ID=function(match,context,isXML){if(typeof context.getElementById!=="undefined"&&!isXML){var m=context.getElementById(match[1]);return m?m.id===match[1]||typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id").nodeValue===match[1]?[m]:undefined:[]}};Expr.filter.ID=function(elem,match){var node=typeof elem.getAttributeNode!=="undefined"&&elem.getAttributeNode("id");return elem.nodeType===1&&node&&node.nodeValue===match}}root.removeChild(form);root=form=null})();(function(){var div=document.createElement("div");div.appendChild(document.createComment(""));if(div.getElementsByTagName("*").length>0){Expr.find.TAG=function(match,context){var results=context.getElementsByTagName(match[1]);if(match[1]==="*"){var tmp=[];for(var i=0;results[i];i++){if(results[i].nodeType===1){tmp.push(results[i])}}results=tmp}return results}}div.innerHTML="<a href='#'></a>";if(div.firstChild&&typeof div.firstChild.getAttribute!=="undefined"&&div.firstChild.getAttribute("href")!=="#"){Expr.attrHandle.href=function(elem){return elem.getAttribute("href",2)}}div=null})();if(document.querySelectorAll){(function(){var oldSizzle=Sizzle,div=document.createElement("div");div.innerHTML="<p class='TEST'></p>";if(div.querySelectorAll&&div.querySelectorAll(".TEST").length===0){return}Sizzle=function(query,context,extra,seed){context=context||document;if(!seed&&context.nodeType===9&&!isXML(context)){try{return makeArray(context.querySelectorAll(query),extra)}catch(e){}}return oldSizzle(query,context,extra,seed)};for(var prop in oldSizzle){Sizzle[prop]=oldSizzle[prop]}div=null})()}(function(){var div=document.createElement("div");div.innerHTML="<div class='test e'></div><div class='test'></div>";if(!div.getElementsByClassName||div.getElementsByClassName("e").length===0){return}div.lastChild.className="e";if(div.getElementsByClassName("e").length===1){return}Expr.order.splice(1,0,"CLASS");Expr.find.CLASS=function(match,context,isXML){if(typeof context.getElementsByClassName!=="undefined"&&!isXML){return context.getElementsByClassName(match[1])}};div=null})();function dirNodeCheck(dir,cur,doneName,checkSet,nodeCheck,isXML){for(var i=0,l=checkSet.length;i<l;i++){var elem=checkSet[i];if(elem){elem=elem[dir];var match=false;while(elem){if(elem.sizcache===doneName){match=checkSet[elem.sizset];break}if(elem.nodeType===1&&!isXML){elem.sizcache=doneName;elem.sizset=i}if(elem.nodeName.toLowerCase()===cur){match=elem;break}elem=elem[dir]}checkSet[i]=match}}}function dirCheck(dir,cur,doneName,checkSet,nodeCheck,isXML){for(var i=0,l=checkSet.length;i<l;i++){var elem=checkSet[i];if(elem){elem=elem[dir];var match=false;while(elem){if(elem.sizcache===doneName){match=checkSet[elem.sizset];break}if(elem.nodeType===1){if(!isXML){elem.sizcache=doneName;elem.sizset=i}if(typeof cur!=="string"){if(elem===cur){match=true;break}}else{if(Sizzle.filter(cur,[elem]).length>0){match=elem;break}}}elem=elem[dir]}checkSet[i]=match}}}var contains=document.compareDocumentPosition?function(a,b){return a.compareDocumentPosition(b)&16}:function(a,b){return a!==b&&(a.contains?a.contains(b):true)};var isXML=function(elem){var documentElement=(elem?elem.ownerDocument||elem:0).documentElement;return documentElement?documentElement.nodeName!=="HTML":false};var posProcess=function(selector,context){var tmpSet=[],later="",match,root=context.nodeType?[context]:context;while((match=Expr.match.PSEUDO.exec(selector))){later+=match[0];selector=selector.replace(Expr.match.PSEUDO,"")}selector=Expr.relative[selector]?selector+"*":selector;for(var i=0,l=root.length;i<l;i++){Sizzle(selector,root[i],tmpSet)}return Sizzle.filter(later,tmpSet)};return Sizzle})();
/*
 * SWFObject v2.1 <http://code.google.com/p/swfobject/>
 * Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis
 * This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
 *
 * Modified for inclusion in Shadowbox.js
 */
S.flash=(function(){var swfobject=function(){var UNDEF="undefined",OBJECT="object",SHOCKWAVE_FLASH="Shockwave Flash",SHOCKWAVE_FLASH_AX="ShockwaveFlash.ShockwaveFlash",FLASH_MIME_TYPE="application/x-shockwave-flash",EXPRESS_INSTALL_ID="SWFObjectExprInst",win=window,doc=document,nav=navigator,domLoadFnArr=[],regObjArr=[],objIdArr=[],listenersArr=[],script,timer=null,storedAltContent=null,storedAltContentId=null,isDomLoaded=false,isExpressInstallActive=false;var ua=function(){var w3cdom=typeof doc.getElementById!=UNDEF&&typeof doc.getElementsByTagName!=UNDEF&&typeof doc.createElement!=UNDEF,playerVersion=[0,0,0],d=null;if(typeof nav.plugins!=UNDEF&&typeof nav.plugins[SHOCKWAVE_FLASH]==OBJECT){d=nav.plugins[SHOCKWAVE_FLASH].description;if(d&&!(typeof nav.mimeTypes!=UNDEF&&nav.mimeTypes[FLASH_MIME_TYPE]&&!nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)){d=d.replace(/^.*\s+(\S+\s+\S+$)/,"$1");playerVersion[0]=parseInt(d.replace(/^(.*)\..*$/,"$1"),10);playerVersion[1]=parseInt(d.replace(/^.*\.(.*)\s.*$/,"$1"),10);playerVersion[2]=/r/.test(d)?parseInt(d.replace(/^.*r(.*)$/,"$1"),10):0}}else{if(typeof win.ActiveXObject!=UNDEF){var a=null,fp6Crash=false;try{a=new ActiveXObject(SHOCKWAVE_FLASH_AX+".7")}catch(e){try{a=new ActiveXObject(SHOCKWAVE_FLASH_AX+".6");playerVersion=[6,0,21];a.AllowScriptAccess="always"}catch(e){if(playerVersion[0]==6){fp6Crash=true}}if(!fp6Crash){try{a=new ActiveXObject(SHOCKWAVE_FLASH_AX)}catch(e){}}}if(!fp6Crash&&a){try{d=a.GetVariable("$version");if(d){d=d.split(" ")[1].split(",");playerVersion=[parseInt(d[0],10),parseInt(d[1],10),parseInt(d[2],10)]}}catch(e){}}}}var u=nav.userAgent.toLowerCase(),p=nav.platform.toLowerCase(),webkit=/webkit/.test(u)?parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,ie=false,windows=p?/win/.test(p):/win/.test(u),mac=p?/mac/.test(p):/mac/.test(u);
/*@cc_on
			ie = true;
			@if (@_win32)
				windows = true;
			@elif (@_mac)
				mac = true;
			@end
		@*/
return{w3cdom:w3cdom,pv:playerVersion,webkit:webkit,ie:ie,win:windows,mac:mac}}();var onDomLoad=function(){if(!ua.w3cdom){return}addDomLoadEvent(main);if(ua.ie&&ua.win){try{doc.write("<script id=__ie_ondomload defer=true src=//:><\/script>");script=getElementById("__ie_ondomload");if(script){addListener(script,"onreadystatechange",checkReadyState)}}catch(e){}}if(ua.webkit&&typeof doc.readyState!=UNDEF){timer=setInterval(function(){if(/loaded|complete/.test(doc.readyState)){callDomLoadFunctions()}},10)}if(typeof doc.addEventListener!=UNDEF){doc.addEventListener("DOMContentLoaded",callDomLoadFunctions,null)}addLoadEvent(callDomLoadFunctions)}();function checkReadyState(){if(script.readyState=="complete"){script.parentNode.removeChild(script);callDomLoadFunctions()}}function callDomLoadFunctions(){if(isDomLoaded){return}if(ua.ie&&ua.win){var s=createElement("span");try{var t=doc.getElementsByTagName("body")[0].appendChild(s);t.parentNode.removeChild(t)}catch(e){return}}isDomLoaded=true;if(timer){clearInterval(timer);timer=null}var dl=domLoadFnArr.length;for(var i=0;i<dl;i++){domLoadFnArr[i]()}}function addDomLoadEvent(fn){if(isDomLoaded){fn()}else{domLoadFnArr[domLoadFnArr.length]=fn}}function addLoadEvent(fn){if(typeof win.addEventListener!=UNDEF){win.addEventListener("load",fn,false)}else{if(typeof doc.addEventListener!=UNDEF){doc.addEventListener("load",fn,false)}else{if(typeof win.attachEvent!=UNDEF){addListener(win,"onload",fn)}else{if(typeof win.onload=="function"){var fnOld=win.onload;win.onload=function(){fnOld();fn()}}else{win.onload=fn}}}}}function main(){var rl=regObjArr.length;for(var i=0;i<rl;i++){var id=regObjArr[i].id;if(ua.pv[0]>0){var obj=getElementById(id);if(obj){regObjArr[i].width=obj.getAttribute("width")?obj.getAttribute("width"):"0";regObjArr[i].height=obj.getAttribute("height")?obj.getAttribute("height"):"0";if(hasPlayerVersion(regObjArr[i].swfVersion)){if(ua.webkit&&ua.webkit<312){fixParams(obj)}setVisibility(id,true)}else{if(regObjArr[i].expressInstall&&!isExpressInstallActive&&hasPlayerVersion("6.0.65")&&(ua.win||ua.mac)){showExpressInstall(regObjArr[i])}else{displayAltContent(obj)}}}}else{setVisibility(id,true)}}}function fixParams(obj){var nestedObj=obj.getElementsByTagName(OBJECT)[0];if(nestedObj){var e=createElement("embed"),a=nestedObj.attributes;if(a){var al=a.length;for(var i=0;i<al;i++){if(a[i].nodeName=="DATA"){e.setAttribute("src",a[i].nodeValue)}else{e.setAttribute(a[i].nodeName,a[i].nodeValue)}}}var c=nestedObj.childNodes;if(c){var cl=c.length;for(var j=0;j<cl;j++){if(c[j].nodeType==1&&c[j].nodeName=="PARAM"){e.setAttribute(c[j].getAttribute("name"),c[j].getAttribute("value"))}}}obj.parentNode.replaceChild(e,obj)}}function showExpressInstall(regObj){isExpressInstallActive=true;var obj=getElementById(regObj.id);if(obj){if(regObj.altContentId){var ac=getElementById(regObj.altContentId);if(ac){storedAltContent=ac;storedAltContentId=regObj.altContentId}}else{storedAltContent=abstractAltContent(obj)}if(!(/%$/.test(regObj.width))&&parseInt(regObj.width,10)<310){regObj.width="310"}if(!(/%$/.test(regObj.height))&&parseInt(regObj.height,10)<137){regObj.height="137"}doc.title=doc.title.slice(0,47)+" - Flash Player Installation";var pt=ua.ie&&ua.win?"ActiveX":"PlugIn",dt=doc.title,fv="MMredirectURL="+win.location+"&MMplayerType="+pt+"&MMdoctitle="+dt,replaceId=regObj.id;if(ua.ie&&ua.win&&obj.readyState!=4){var newObj=createElement("div");replaceId+="SWFObjectNew";newObj.setAttribute("id",replaceId);obj.parentNode.insertBefore(newObj,obj);obj.style.display="none";var fn=function(){obj.parentNode.removeChild(obj)};addListener(win,"onload",fn)}createSWF({data:regObj.expressInstall,id:EXPRESS_INSTALL_ID,width:regObj.width,height:regObj.height},{flashvars:fv},replaceId)}}function displayAltContent(obj){if(ua.ie&&ua.win&&obj.readyState!=4){var el=createElement("div");obj.parentNode.insertBefore(el,obj);el.parentNode.replaceChild(abstractAltContent(obj),el);obj.style.display="none";var fn=function(){obj.parentNode.removeChild(obj)};addListener(win,"onload",fn)}else{obj.parentNode.replaceChild(abstractAltContent(obj),obj)}}function abstractAltContent(obj){var ac=createElement("div");if(ua.win&&ua.ie){ac.innerHTML=obj.innerHTML}else{var nestedObj=obj.getElementsByTagName(OBJECT)[0];if(nestedObj){var c=nestedObj.childNodes;if(c){var cl=c.length;for(var i=0;i<cl;i++){if(!(c[i].nodeType==1&&c[i].nodeName=="PARAM")&&!(c[i].nodeType==8)){ac.appendChild(c[i].cloneNode(true))}}}}}return ac}function createSWF(attObj,parObj,id){var r,el=getElementById(id);if(el){if(typeof attObj.id==UNDEF){attObj.id=id}if(ua.ie&&ua.win){var att="";for(var i in attObj){if(attObj[i]!=Object.prototype[i]){if(i.toLowerCase()=="data"){parObj.movie=attObj[i]}else{if(i.toLowerCase()=="styleclass"){att+=' class="'+attObj[i]+'"'}else{if(i.toLowerCase()!="classid"){att+=" "+i+'="'+attObj[i]+'"'}}}}}var par="";for(var j in parObj){if(parObj[j]!=Object.prototype[j]){par+='<param name="'+j+'" value="'+parObj[j]+'" />'}}el.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+att+">"+par+"</object>";objIdArr[objIdArr.length]=attObj.id;r=getElementById(attObj.id)}else{if(ua.webkit&&ua.webkit<312){var e=createElement("embed");e.setAttribute("type",FLASH_MIME_TYPE);for(var k in attObj){if(attObj[k]!=Object.prototype[k]){if(k.toLowerCase()=="data"){e.setAttribute("src",attObj[k])}else{if(k.toLowerCase()=="styleclass"){e.setAttribute("class",attObj[k])}else{if(k.toLowerCase()!="classid"){e.setAttribute(k,attObj[k])}}}}}for(var l in parObj){if(parObj[l]!=Object.prototype[l]){if(l.toLowerCase()!="movie"){e.setAttribute(l,parObj[l])}}}el.parentNode.replaceChild(e,el);r=e}else{var o=createElement(OBJECT);o.setAttribute("type",FLASH_MIME_TYPE);for(var m in attObj){if(attObj[m]!=Object.prototype[m]){if(m.toLowerCase()=="styleclass"){o.setAttribute("class",attObj[m])}else{if(m.toLowerCase()!="classid"){o.setAttribute(m,attObj[m])}}}}for(var n in parObj){if(parObj[n]!=Object.prototype[n]&&n.toLowerCase()!="movie"){createObjParam(o,n,parObj[n])}}el.parentNode.replaceChild(o,el);r=o}}}return r}function createObjParam(el,pName,pValue){var p=createElement("param");p.setAttribute("name",pName);p.setAttribute("value",pValue);el.appendChild(p)}function removeSWF(id){var obj=getElementById(id);if(obj&&(obj.nodeName=="OBJECT"||obj.nodeName=="EMBED")){if(ua.ie&&ua.win){if(obj.readyState==4){removeObjectInIE(id)}else{win.attachEvent("onload",function(){removeObjectInIE(id)})}}else{obj.parentNode.removeChild(obj)}}}function removeObjectInIE(id){var obj=getElementById(id);if(obj){for(var i in obj){if(typeof obj[i]=="function"){obj[i]=null}}obj.parentNode.removeChild(obj)}}function getElementById(id){var el=null;try{el=doc.getElementById(id)}catch(e){}return el}function createElement(el){return doc.createElement(el)}function addListener(target,eventType,fn){target.attachEvent(eventType,fn);listenersArr[listenersArr.length]=[target,eventType,fn]}function hasPlayerVersion(rv){var pv=ua.pv,v=rv.split(".");v[0]=parseInt(v[0],10);v[1]=parseInt(v[1],10)||0;v[2]=parseInt(v[2],10)||0;return(pv[0]>v[0]||(pv[0]==v[0]&&pv[1]>v[1])||(pv[0]==v[0]&&pv[1]==v[1]&&pv[2]>=v[2]))?true:false}function createCSS(sel,decl){if(ua.ie&&ua.mac){return}var h=doc.getElementsByTagName("head")[0],s=createElement("style");s.setAttribute("type","text/css");s.setAttribute("media","screen");if(!(ua.ie&&ua.win)&&typeof doc.createTextNode!=UNDEF){s.appendChild(doc.createTextNode(sel+" {"+decl+"}"))}h.appendChild(s);if(ua.ie&&ua.win&&typeof doc.styleSheets!=UNDEF&&doc.styleSheets.length>0){var ls=doc.styleSheets[doc.styleSheets.length-1];if(typeof ls.addRule==OBJECT){ls.addRule(sel,decl)}}}function setVisibility(id,isVisible){var v=isVisible?"visible":"hidden";if(isDomLoaded&&getElementById(id)){getElementById(id).style.visibility=v}else{createCSS("#"+id,"visibility:"+v)}}function urlEncodeIfNecessary(s){var regex=/[\\\"<>\.;]/;var hasBadChars=regex.exec(s)!=null;return hasBadChars?encodeURIComponent(s):s}var cleanup=function(){if(ua.ie&&ua.win){window.attachEvent("onunload",function(){var ll=listenersArr.length;for(var i=0;i<ll;i++){listenersArr[i][0].detachEvent(listenersArr[i][1],listenersArr[i][2])}var il=objIdArr.length;for(var j=0;j<il;j++){removeSWF(objIdArr[j])}for(var k in ua){ua[k]=null}ua=null;for(var l in swfobject){swfobject[l]=null}swfobject=null})}}();return{registerObject:function(objectIdStr,swfVersionStr,xiSwfUrlStr){if(!ua.w3cdom||!objectIdStr||!swfVersionStr){return}var regObj={};regObj.id=objectIdStr;regObj.swfVersion=swfVersionStr;regObj.expressInstall=xiSwfUrlStr?xiSwfUrlStr:false;regObjArr[regObjArr.length]=regObj;setVisibility(objectIdStr,false)},getObjectById:function(objectIdStr){var r=null;if(ua.w3cdom){var o=getElementById(objectIdStr);if(o){var n=o.getElementsByTagName(OBJECT)[0];if(!n||(n&&typeof o.SetVariable!=UNDEF)){r=o}else{if(typeof n.SetVariable!=UNDEF){r=n}}}}return r},embedSWF:function(swfUrlStr,replaceElemIdStr,widthStr,heightStr,swfVersionStr,xiSwfUrlStr,flashvarsObj,parObj,attObj){if(!ua.w3cdom||!swfUrlStr||!replaceElemIdStr||!widthStr||!heightStr||!swfVersionStr){return}widthStr+="";heightStr+="";if(hasPlayerVersion(swfVersionStr)){setVisibility(replaceElemIdStr,false);var att={};if(attObj&&typeof attObj===OBJECT){for(var i in attObj){if(attObj[i]!=Object.prototype[i]){att[i]=attObj[i]}}}att.data=swfUrlStr;att.width=widthStr;att.height=heightStr;var par={};if(parObj&&typeof parObj===OBJECT){for(var j in parObj){if(parObj[j]!=Object.prototype[j]){par[j]=parObj[j]}}}if(flashvarsObj&&typeof flashvarsObj===OBJECT){for(var k in flashvarsObj){if(flashvarsObj[k]!=Object.prototype[k]){if(typeof par.flashvars!=UNDEF){par.flashvars+="&"+k+"="+flashvarsObj[k]}else{par.flashvars=k+"="+flashvarsObj[k]}}}}addDomLoadEvent(function(){createSWF(att,par,replaceElemIdStr);if(att.id==replaceElemIdStr){setVisibility(replaceElemIdStr,true)}})}else{if(xiSwfUrlStr&&!isExpressInstallActive&&hasPlayerVersion("6.0.65")&&(ua.win||ua.mac)){isExpressInstallActive=true;setVisibility(replaceElemIdStr,false);addDomLoadEvent(function(){var regObj={};regObj.id=regObj.altContentId=replaceElemIdStr;regObj.width=widthStr;regObj.height=heightStr;regObj.expressInstall=xiSwfUrlStr;showExpressInstall(regObj)})}}},getFlashPlayerVersion:function(){return{major:ua.pv[0],minor:ua.pv[1],release:ua.pv[2]}},hasFlashPlayerVersion:hasPlayerVersion,createSWF:function(attObj,parObj,replaceElemIdStr){if(ua.w3cdom){return createSWF(attObj,parObj,replaceElemIdStr)}else{return undefined}},removeSWF:function(objElemIdStr){if(ua.w3cdom){removeSWF(objElemIdStr)}},createCSS:function(sel,decl){if(ua.w3cdom){createCSS(sel,decl)}},addDomLoadEvent:addDomLoadEvent,addLoadEvent:addLoadEvent,getQueryParamValue:function(param){var q=doc.location.search||doc.location.hash;if(param==null){return urlEncodeIfNecessary(q)}if(q){var pairs=q.substring(1).split("&");for(var i=0;i<pairs.length;i++){if(pairs[i].substring(0,pairs[i].indexOf("="))==param){return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(isExpressInstallActive&&storedAltContent){var obj=getElementById(EXPRESS_INSTALL_ID);if(obj){obj.parentNode.replaceChild(storedAltContent,obj);if(storedAltContentId){setVisibility(storedAltContentId,true);if(ua.ie&&ua.win){storedAltContent.style.display="block"}}storedAltContent=null;storedAltContentId=null;isExpressInstallActive=false}}}}}();return swfobject})();S.lang={code:"en",of:"of",loading:"loading",cancel:"Cancel",next:"Next",previous:"Previous",play:"Play",pause:"Pause",close:"Close",errors:{single:'You must install the <a href="{0}">{1}</a> browser plugin to view this content.',shared:'You must install both the <a href="{0}">{1}</a> and <a href="{2}">{3}</a> browser plugins to view this content.',either:'You must install either the <a href="{0}">{1}</a> or the <a href="{2}">{3}</a> browser plugin to view this content.'}};var pre,proxyId="sb-drag-proxy",dragData,dragProxy,dragTarget;function resetDrag(){dragData={x:0,y:0,startX:null,startY:null}}function updateProxy(){var dims=S.dimensions;apply(dragProxy.style,{height:dims.innerHeight+"px",width:dims.innerWidth+"px"})}function enableDrag(){resetDrag();var style=["position:absolute","cursor:"+(S.isGecko?"-moz-grab":"move"),"background-color:"+(S.isIE?"#fff;filter:alpha(opacity=0)":"transparent")].join(";");S.appendHTML(S.skin.body,'<div id="'+proxyId+'" style="'+style+'"></div>');dragProxy=get(proxyId);updateProxy();addEvent(dragProxy,"mousedown",startDrag)}function disableDrag(){if(dragProxy){removeEvent(dragProxy,"mousedown",startDrag);remove(dragProxy);dragProxy=null}dragTarget=null}function startDrag(e){preventDefault(e);var xy=getPageXY(e);dragData.startX=xy[0];dragData.startY=xy[1];dragTarget=get(S.player.id);addEvent(document,"mousemove",positionDrag);addEvent(document,"mouseup",endDrag);if(S.isGecko){dragProxy.style.cursor="-moz-grabbing"}}function positionDrag(e){var player=S.player,dims=S.dimensions,xy=getPageXY(e);var moveX=xy[0]-dragData.startX;dragData.startX+=moveX;dragData.x=Math.max(Math.min(0,dragData.x+moveX),dims.innerWidth-player.width);var moveY=xy[1]-dragData.startY;dragData.startY+=moveY;dragData.y=Math.max(Math.min(0,dragData.y+moveY),dims.innerHeight-player.height);apply(dragTarget.style,{left:dragData.x+"px",top:dragData.y+"px"})}function endDrag(){removeEvent(document,"mousemove",positionDrag);removeEvent(document,"mouseup",endDrag);if(S.isGecko){dragProxy.style.cursor="-moz-grab"}}S.img=function(obj,id){this.obj=obj;this.id=id;this.ready=false;var self=this;pre=new Image();pre.onload=function(){self.height=obj.height?parseInt(obj.height,10):pre.height;self.width=obj.width?parseInt(obj.width,10):pre.width;self.ready=true;pre.onload=null;pre=null};pre.src=obj.content};S.img.ext=["bmp","gif","jpg","jpeg","png"];S.img.prototype={append:function(body,dims){var img=document.createElement("img");img.id=this.id;img.src=this.obj.content;img.style.position="absolute";var height,width;if(dims.oversized&&S.options.handleOversize=="resize"){height=dims.innerHeight;width=dims.innerWidth}else{height=this.height;width=this.width}img.setAttribute("height",height);img.setAttribute("width",width);body.appendChild(img)},remove:function(){var el=get(this.id);if(el){remove(el)}disableDrag();if(pre){pre.onload=null;pre=null}},onLoad:function(){var dims=S.dimensions;if(dims.oversized&&S.options.handleOversize=="drag"){enableDrag()}},onWindowResize:function(){var dims=S.dimensions;switch(S.options.handleOversize){case"resize":var el=get(this.id);el.height=dims.innerHeight;el.width=dims.innerWidth;break;case"drag":if(dragTarget){var top=parseInt(S.getStyle(dragTarget,"top")),left=parseInt(S.getStyle(dragTarget,"left"));if(top+this.height<dims.innerHeight){dragTarget.style.top=dims.innerHeight-this.height+"px"}if(left+this.width<dims.innerWidth){dragTarget.style.left=dims.innerWidth-this.width+"px"}updateProxy()}break}}};S.html=function(obj,id){this.obj=obj;this.id=id;this.height=obj.height?parseInt(obj.height,10):300;this.width=obj.width?parseInt(obj.width,10):500};S.html.prototype={append:function(body,dims){var div=document.createElement("div");div.id=this.id;div.className="html";div.innerHTML=this.obj.content;body.appendChild(div)},remove:function(){var el=get(this.id);if(el){remove(el)}}};S.swf=function(obj,id){this.obj=obj;this.id=id;this.height=obj.height?parseInt(obj.height,10):300;this.width=obj.width?parseInt(obj.width,10):300};S.swf.ext=["swf"];S.swf.prototype={append:function(body,dims){var tmp=document.createElement("div");tmp.id=this.id;body.appendChild(tmp);var height=dims.innerHeight,width=dims.innerWidth,swf=this.obj.content,version=S.options.flashVersion,express=S.path+"expressInstall.swf",flashvars=S.options.flashVars,params=S.options.flashParams;S.flash.embedSWF(swf,this.id,width,height,version,express,flashvars,params)},remove:function(){S.flash.expressInstallCallback();S.flash.removeSWF(this.id)},onWindowResize:function(){var dims=S.dimensions,el=get(this.id);el.height=dims.innerHeight;el.width=dims.innerWidth}};var overlayOn=false,visibilityCache=[],pngIds=["sb-nav-close","sb-nav-next","sb-nav-play","sb-nav-pause","sb-nav-previous"],container,overlay,wrapper,doWindowResize=true;function animate(el,property,to,duration,callback){var isOpacity=(property=="opacity"),anim=isOpacity?S.setOpacity:function(el,value){el.style[property]=""+value+"px"};if(duration==0||(!isOpacity&&!S.options.animate)||(isOpacity&&!S.options.animateFade)){anim(el,to);if(callback){callback()}return}var from=parseFloat(S.getStyle(el,property))||0;var delta=to-from;if(delta==0){if(callback){callback()}return}duration*=1000;var begin=now(),ease=S.ease,end=begin+duration,time;var interval=setInterval(function(){time=now();if(time>=end){clearInterval(interval);interval=null;anim(el,to);if(callback){callback()}}else{anim(el,from+ease((time-begin)/duration)*delta)}},10)}function setSize(){container.style.height=S.getWindowSize("Height")+"px";container.style.width=S.getWindowSize("Width")+"px"}function setPosition(){container.style.top=document.documentElement.scrollTop+"px";container.style.left=document.documentElement.scrollLeft+"px"}function toggleTroubleElements(on){if(on){each(visibilityCache,function(i,el){el[0].style.visibility=el[1]||""})}else{visibilityCache=[];each(S.options.troubleElements,function(i,tag){each(document.getElementsByTagName(tag),function(j,el){visibilityCache.push([el,el.style.visibility]);el.style.visibility="hidden"})})}}function toggleNav(id,on){var el=get("sb-nav-"+id);if(el){el.style.display=on?"":"none"}}function toggleLoading(on,callback){var loading=get("sb-loading"),playerName=S.getCurrent().player,anim=(playerName=="img"||playerName=="html");if(on){S.setOpacity(loading,0);loading.style.display="block";var wrapped=function(){S.clearOpacity(loading);if(callback){callback()}};if(anim){animate(loading,"opacity",1,S.options.fadeDuration,wrapped)}else{wrapped()}}else{var wrapped=function(){loading.style.display="none";S.clearOpacity(loading);if(callback){callback()}};if(anim){animate(loading,"opacity",0,S.options.fadeDuration,wrapped)}else{wrapped()}}}function buildBars(callback){var obj=S.getCurrent();get("sb-title-inner").innerHTML=obj.title||"";var close,next,play,pause,previous;if(S.options.displayNav){close=true;var len=S.gallery.length;if(len>1){if(S.options.continuous){next=previous=true}else{next=(len-1)>S.current;previous=S.current>0}}if(S.options.slideshowDelay>0&&S.hasNext()){pause=!S.isPaused();play=!pause}}else{close=next=play=pause=previous=false}toggleNav("close",close);toggleNav("next",next);toggleNav("play",play);toggleNav("pause",pause);toggleNav("previous",previous);var counter="";if(S.options.displayCounter&&S.gallery.length>1){var len=S.gallery.length;if(S.options.counterType=="skip"){var i=0,end=len,limit=parseInt(S.options.counterLimit)||0;if(limit<len&&limit>2){var h=Math.floor(limit/2);i=S.current-h;if(i<0){i+=len}end=S.current+(limit-h);if(end>len){end-=len}}while(i!=end){if(i==len){i=0}counter+='<a onclick="Shadowbox.change('+i+');"';if(i==S.current){counter+=' class="sb-counter-current"'}counter+=">"+(++i)+"</a>"}}else{counter=[S.current+1,S.lang.of,len].join(" ")}}get("sb-counter").innerHTML=counter;callback()}function showBars(callback){var titleInner=get("sb-title-inner"),infoInner=get("sb-info-inner"),duration=0.35;titleInner.style.visibility=infoInner.style.visibility="";if(titleInner.innerHTML!=""){animate(titleInner,"marginTop",0,duration)}animate(infoInner,"marginTop",0,duration,callback)}function hideBars(anim,callback){var title=get("sb-title"),info=get("sb-info"),titleHeight=title.offsetHeight,infoHeight=info.offsetHeight,titleInner=get("sb-title-inner"),infoInner=get("sb-info-inner"),duration=(anim?0.35:0);animate(titleInner,"marginTop",titleHeight,duration);animate(infoInner,"marginTop",infoHeight*-1,duration,function(){titleInner.style.visibility=infoInner.style.visibility="hidden";callback()})}function adjustHeight(height,top,anim,callback){var wrapperInner=get("sb-wrapper-inner"),duration=(anim?S.options.resizeDuration:0);animate(wrapper,"top",top,duration);animate(wrapperInner,"height",height,duration,callback)}function adjustWidth(width,left,anim,callback){var duration=(anim?S.options.resizeDuration:0);animate(wrapper,"left",left,duration);animate(wrapper,"width",width,duration,callback)}function setDimensions(height,width){var bodyInner=get("sb-body-inner"),height=parseInt(height),width=parseInt(width),topBottom=wrapper.offsetHeight-bodyInner.offsetHeight,leftRight=wrapper.offsetWidth-bodyInner.offsetWidth,maxHeight=overlay.offsetHeight,maxWidth=overlay.offsetWidth,padding=parseInt(S.options.viewportPadding)||20,preserveAspect=(S.player&&S.options.handleOversize!="drag");return S.setDimensions(height,width,maxHeight,maxWidth,topBottom,leftRight,padding,preserveAspect)}var K={};K.markup='<div id="sb-container"><div id="sb-overlay"></div><div id="sb-wrapper"><div id="sb-title"><div id="sb-title-inner"></div></div><div id="sb-wrapper-inner"><div id="sb-body"><div id="sb-body-inner"></div><div id="sb-loading"><div id="sb-loading-inner"><span>{loading}</span></div></div></div></div><div id="sb-info"><div id="sb-info-inner"><div id="sb-counter"></div><div id="sb-nav"><a id="sb-nav-close" title="{close}" onclick="Shadowbox.close();closebox = 1"></a><a id="sb-nav-next" title="{next}" onclick="Shadowbox.next()"></a><a id="sb-nav-play" title="{play}" onclick="Shadowbox.play()"></a><a id="sb-nav-pause" title="{pause}" onclick="Shadowbox.pause()"></a><a id="sb-nav-previous" title="{previous}" onclick="Shadowbox.previous()"></a></div></div></div></div></div>';K.options={animSequence:"sync",counterLimit:10,counterType:"default",displayCounter:true,displayNav:true,fadeDuration:0.35,initialHeight:160,initialWidth:320,modal:false,overlayColor:"#000",overlayOpacity:0.5,resizeDuration:0.35,showOverlay:true,troubleElements:["select","object","embed","canvas"]};K.init=function(){S.appendHTML(document.body,sprintf(K.markup,S.lang));K.body=get("sb-body-inner");container=get("sb-container");overlay=get("sb-overlay");wrapper=get("sb-wrapper");if(!supportsFixed){container.style.position="absolute"}if(!supportsOpacity){var el,m,re=/url\("(.*\.png)"\)/;each(pngIds,function(i,id){el=get(id);if(el){m=S.getStyle(el,"backgroundImage").match(re);if(m){el.style.backgroundImage="none";el.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,src="+m[1]+",sizingMethod=scale);"}}})}var timer;addEvent(window,"resize",function(){if(timer){clearTimeout(timer);timer=null}if(open){timer=setTimeout(K.onWindowResize,10)}})};K.onOpen=function(obj,callback){doWindowResize=false;container.style.display="block";setSize();var dims=setDimensions(S.options.initialHeight,S.options.initialWidth);adjustHeight(dims.innerHeight,dims.top);adjustWidth(dims.width,dims.left);if(S.options.showOverlay){overlay.style.backgroundColor=S.options.overlayColor;S.setOpacity(overlay,0);if(!S.options.modal){addEvent(overlay,"click",S.close)}overlayOn=true}if(!supportsFixed){setPosition();addEvent(window,"scroll",setPosition)}toggleTroubleElements();container.style.visibility="visible";if(overlayOn){animate(overlay,"opacity",S.options.overlayOpacity,S.options.fadeDuration,callback)}else{callback()}};K.onLoad=function(changing,callback){toggleLoading(true);while(K.body.firstChild){remove(K.body.firstChild)}hideBars(changing,function(){if(!open){return}if(!changing){wrapper.style.visibility="visible"}buildBars(callback)})};K.onReady=function(callback){if(!open){return}var player=S.player,dims=setDimensions(player.height,player.width);var wrapped=function(){showBars(callback)};switch(S.options.animSequence){case"hw":adjustHeight(dims.innerHeight,dims.top,true,function(){adjustWidth(dims.width,dims.left,true,wrapped)});break;case"wh":adjustWidth(dims.width,dims.left,true,function(){adjustHeight(dims.innerHeight,dims.top,true,wrapped)});break;default:adjustWidth(dims.width,dims.left,true);adjustHeight(dims.innerHeight,dims.top,true,wrapped)}};K.onShow=function(callback){toggleLoading(false,callback);doWindowResize=true};K.onClose=function(){if(!supportsFixed){removeEvent(window,"scroll",setPosition)}removeEvent(overlay,"click",S.close);wrapper.style.visibility="hidden";var callback=function(){container.style.visibility="hidden";container.style.display="none";toggleTroubleElements(true)};if(overlayOn){animate(overlay,"opacity",0,S.options.fadeDuration,callback)}else{callback()}};K.onPlay=function(){toggleNav("play",false);toggleNav("pause",true)};K.onPause=function(){toggleNav("pause",false);toggleNav("play",true)};K.onWindowResize=function(){if(!doWindowResize){return}setSize();var player=S.player,dims=setDimensions(player.height,player.width);adjustWidth(dims.width,dims.left);adjustHeight(dims.innerHeight,dims.top);if(player.onWindowResize){player.onWindowResize()}};S.skin=K;window.Shadowbox=S})(window);


