var debugSCET = true;

//jqN(function(){
jqN(document).ready(function() {			   
	//alert('rolling up search');
	jqN('#search-field').focus(function(){searchField()});	
});

/******** SEARCH **********/
var searchKeywords = '';
function searchField(){
	jqN('#search .error').slideUp('fast');
}
function videoSearch(thisForm,e){
	
	if(thisForm.searchField.value == "Search more videos" || thisForm.searchField.value == ""){
		jqN('#search .error').slideDown('fast');
	}else{
		//e.preventDefault();
		searchKeywords = thisForm.searchField.value;
		var searchFilter = jqN('input[name=searchFilter]:checked').val();
		if(searchFilter == 'nbc'){
			window.location = "http://www.nbc.com/app/search/?keywords="+searchKeywords+"&type=NBCVIDEO";
			return false;
		}
		jqN('#search-results').html(ajaxLoader()).slideDown('fast');
		var url = jqN(thisForm).attr('action');
        if (siteName == 'NBC Video Library' || siteName == 'The More You Know') {
		    var showFilter = "type=NBCVIDEO";
        } else {
		    var showFilter = "showname=" + siteName + "&type=NBCVIDEO";
        }
		jqN.ajax({
			type: "GET",
			//url: "localhostGateway.php",
			//data:	"url="+url+"&"+showFilter+"&keywords="+thisForm.searchField.value,
			url: url,
			data:	showFilter+"&keywords="+jqN.trim(thisForm.searchField.value),
			dataType: "json",
			beforeSend: function(xhr){xhr.setRequestHeader("X-Framework-JSON-Request", "PLAINJSON");},
			success: 		scetLoadResults,
			error: 			function(XMLHttpRequest, textStatus, errorThrown){}
		});
	}
	return false;
}

function validateBrowseSearchForm(thisForm,e){
	
	if(thisForm.searchFor.value == "Search more videos" || thisForm.searchFor.value == ""){
		jqN('#search .error').slideDown('fast');
		return false;
	}
}

function closeResults(){
	jqN('#search-results').slideUp('fast').html();
}

function listTemplate(h, d, u, t, titleSize, onclick, width, height){
	titleSize = titleSize || 'h5';
	onclick = onclick || '';
	if (onclick) {
		onclick = ' onclick="' + onclick + '"';
	}
	var size = '';
	if (width && height) {
	   size = 'width="' + width + '" height="' + height + '" ';
	}

	return '<li><a class="border" href="' + u + '"' + onclick +'><img ' + size + 'alt="' + h.replace(/[^a-zA-Z 0-9]+/g,'') + '" src="' + t + '"/></a><' + titleSize + '><a href="' + u + '"' + onclick +'>' + h + '</a></' + titleSize + '><p>' + d + '</p></li>';
}

function scetLoadResults(results){
	debug(results);
	jqN('#search-results').slideUp('fast');
	var searchObj = results.search.NBCVIDEO;
	var output = '<h4>YOUR SEARCH RESULTS FOR "'+searchKeywords.replace(/[^a-zA-Z 0-9]+/g,'')+'"</h4>';
	if(searchObj == null){
		output += '<p>No Results</p>';
	}else{
		var searchTotal = searchObj.result_count;
		if(searchTotal > 0){
			output += '<ul>';
			jqN(searchObj.results).each(function(i){
				if(i <= 4)
					output += listTemplate(this.title,this.summaryText,this.url,getMezzanine(this.thumbnail,'106','59'),'',106,59);
			});
		output += '</ul>';
		if(searchTotal > 5)
			output += '<a href="http://www.nbc.com/app/search/?keywords='+searchKeywords+'&show_name=' + siteName + '&type=NBCVIDEO" class="search-more-results">More Results</a>';
		output += '<a href="javascript:void(0);" class="search-close-results right">Close Results</a>';
		}else{
			output += '<p>No Results</p>';
		}
	}
	output = output.replace(/b>/gi,'strong>');
	jqN('input[name=searchField]').val("Search more videos");
	jqN('#search-results').html(output).slideDown('fast');	
	jqN('.search-close-results').live('click',closeResults);
	return false;
}
/******** END SEARCH **********/

/************* UTILITIES *************/
function ajaxLoader(){
	return '<div class="ajax-loader"><img src="/assets/images/ajax/ajax-loader.gif" alt="Loading...." /></div>';
}

function getMezzanine(str,w,h){
	str = str || '';
	w = w || 0;
	h = h || 0;
	
	var r = [];
	r[0] = ["http://video-origin.nbcuni.com/mezzthumb","http://video.nbc.com/player/mezzanine/image.php?w="+w+"&h="+h+"&path="];
	r[1] = ["http://video.nbcuni.com/nbcrewind2/thumb/","http://video.nbc.com/player/mezzanine/image.php?w="+w+"&h="+h+"&path=nbcrewind2/"];
	r[2] = ["http://video.nbcuni.com/nbc2/thumb/","http://video.nbc.com/player/mezzanine/image.php?w="+w+"&h="+h+"&path=nbc2/"];
	r[3] = ["http://video.nbc.com/nbc2/thumb/","http://video.nbc.com/player/mezzanine/image.php?w="+w+"&h="+h+"&path=nbc2/"];
	r[4] = ["http://video.nbc.com/nbcrewind2/thumb/","http://video.nbc.com/player/mezzanine/image.php?w="+w+"&h="+h+"&path=nbcrewind2/"];
	r[5] = ["_large","_mezzn"];
	r[6] = ["http://video.nbc.com/nbc-hls/thumb/","http://video.nbc.com/player/mezzanine/image.php?w="+w+"&h="+h+"&path=nbc-hls/"];
	for(var i=0;i<r.length;i++){
		str = str.replace(r[i][0],r[i][1]);
	}

	return str+"&trusted=yes";
}

function debug(s){
	if(window.console && window.console.log && !jqN.browser.msie && debugSCET==true)
		console.log(s);
}

function tooltip(e, txt, o) {
	var defaults = {
		width: 300,
		fill: 'rgb(254,255,221)',
		cornerRadius: 10,
		padding: 10,
		strokeWidth: 0,
		spikeLength: 0,
		spikeGirth: 0,
		shadow: true,
		shadowOffsetX: 0,
		shadowOffsetY: 3,
		shadowBlur: 8,
		shadowColor: 'rgba(0,0,0,.9)',
		shadowOverlap: false,
		noShadowOpts: {strokeStyle: '#999', strokeWidth: 2},
		positions: 'bottom',
		textzIndex: 99999999,
		boxzIndex: 99999998,
		wrapperzIndex: 99999997
	};
	var opts = jqN.extend(false, defaults, o);
	
		e.bt(txt, opts);
	
}


/************* END UTILITIES *************/


	/**
	 * Refresh 300x250, 728x90, & 120x60
	 */
	function _refreshMetrics(adParam) {
		if (typeof genSetRandDARTNumber == 'function') {
			genSetRandDARTNumber();
		} else {
			randDARTNumber = Math.round(Math.random()*1000000000000);
		}
		
		var ad728x90Uri = '/assets/scet/common/frames/ads/?size=728x90&showCode=' + adParam.showCode + '&sub=' + adParam.sub + '&sub2=' + adParam.sub2 + '&daypart=' + adParam.dayPart + '&genre=' + adParam.genre + (adParam.sect ? '&sect=' + adParam.sect : '');
		var ad300x250Uri = '/assets/scet/common/frames/ads/?size=300x250&showCode=' + adParam.showCode + '&sub=' + adParam.sub + '&sub2=' + adParam.sub2 + '&daypart=' + adParam.dayPart + '&genre=' + adParam.genre + (adParam.sect ? '&sect=' + adParam.sect : '');
		var ad120x60Uri = '/assets/scet/common/frames/ads/?size=120x60&showCode=' + adParam.showCode + '&sub=' + adParam.sub + '&sub2=' + adParam.sub2 + '&daypart=' + adParam.dayPart + '&genre=' + adParam.genre + (adParam.sect ? '&sect=' + adParam.sect : '');
			
		if (typeof s != 'undefined' && typeof s.t == 'function') {
			s.t();
		} 
		
		try {
			window.ad728x90.location.href = ad728x90Uri;
		} catch(err) {}
		
		try {
			window.ad300x250.location.href = ad300x250Uri;
		} catch(err) {}
		
		try {
			window.ad120x60.location.href = ad120x60Uri;
		} catch(err) {}
	}


/***
 * Construct 300x250 url to provide a fallback doubleclick url for FreeWheel ad engine
 ***/
function getFallbackDartUrl(adParam) {
    var adUrl = '';
    if (!isFullEpisode) {
        var strSize = '300x250';
        var intPos  = (strSize == '300x250') ? 7 : ((strSize == '120x60') ? 8 : 1);
        var intTile = (strSize == '300x250' || strSize == '120x60') ? 7 : 1;
        var railAd  = strSize == '728x90' ? ';dcopt=ist' : '';

        adUrl = 'dfp_300=' + encodeURIComponent('http://ad.doubleclick.net/adj/nbcu.nbc/' + adParam.showCode + '_' + adParam.sub + ';site=nbc;sect=' + adParam.sect + ';sub=' + adParam.sub + ';sub2=' + adParam.sub2 + ';genre=' + adParam.genre + ';daypart=' + adParam.dayPart + ';!category=' + adParam.showCode + ';!category=js;!category=nbc;!category=noexpand;network=tvn;sz=' + strSize + ';tagtype=js;uri=;pos=' + intPos + ';tile=' + intTile + railAd + ';ord=' + randDARTNumber + '?');

    }
    return adUrl;
}


