/*
 * Brightcove Integration with tampabay.com pages
 * 
 * This javascript object (and supporting function calls) should handle all brightcove integration
 * with any tampabay.com page that loads a video teaser, or with the main video page
 * 
 * @author rcurts
 * 
 */

/* 
 * --------------------------------------------------------------------------------------------
 * Brightcove static javascript properties and methods. These are called and handled by the
 * brightcove experience javascript, and are not a part of the tampabay.com video module.
 * --------------------------------------------------------------------------------------------
 */

var console, brightcove;

//-- Brightcove Properties --------------------------------------------------------------------
var tpc_v_bcExp, tpc_v_modVP, tpc_v_modExp, tpc_v_modCon;

// -- Brightcove Functions
// ---------------------------------------------------------------------

/*
 * Called by the brightcove experience
 */
function onTemplateLoaded(experienceID) {
	if (tpcv.debug) console.log("Experience loaded ID=" + experienceID);

	tpc_v_bcExp  = brightcove.getExperience(experienceID);
	tpc_v_modVP  = tpc_v_bcExp.getModule(APIModules.VIDEO_PLAYER);
	tpc_v_modExp = tpc_v_bcExp.getModule(APIModules.EXPERIENCE);
	tpc_v_modCon = tpc_v_bcExp.getModule(APIModules.CONTENT);

	tpc_v_modExp.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
	tpc_v_modExp.addEventListener(BCExperienceEvent.CONTENT_LOAD, onContentLoad);
	tpc_v_modCon.addEventListener(BCContentEvent.VIDEO_LOAD, onVideoLoad); 
}

//-- Brightcove Listeners ---------------------------------------------------------------------

/*
 * Handles brightcove template ready events
 */	
function onTemplateReady(evt) {
	tpcv.bc_init = true;
	if (tpcv.debug) console.log("Brightcove template has been initialized.");
}

/*
 * Handles brightcove content load events
 */
function onContentLoad(evt) {
}

/*
 * Handles brightcove video load events
 */
function onVideoLoad(evt) {	 
	if (tpcv.debug) console.log("Video Load event fired")
	
	var _autoplay = tpc.param('ba', 'true');
	if (tpcv.debug) console.log("Autoplay is set to: " + _autoplay);
	
	if (_autoplay != 'false') {
		tpc_v_modVP.loadVideo(evt.video.id);	
	} else {
		tpc_v_modVP.cueVideo(evt.video.id);		
	}
}

  
/* 
 * --------------------------------------------------------------------------------------------
 * Video object for tampabay.com video functionality.  This will handle all of the necessary
 * functionality for anything to do with video and brightcove on the site.  Everything comes
 * down to three functions:
 * 
 * play()   <-- plays something in the brightcove player
 * search() <-- gets a search result by tag, keyword, or playlist
 * slider() <-- creates a jquery "carousel" to put on right rails of pages 
 * -------------------------------------------------------------------------------------------
 */

// define the object
function tpcv() {}

//---------------------------------------------------------------------------------------------
//-- Static properties 
 
// debug flag
tpcv.debug = false;

// search types
tpcv.PID_SEARCH = 1;
tpcv.TAG_SEARCH = 2;
tpcv.TEXT_SEARCH = 3;
	
// default search text
tpcv.defst = 'Quick Video Search...';
	
// ---------------------------------------------------------------------------------------------
// -- Brightcove Properties

// Token used to identify us to brightcove's server. Used for all RESTful
// communication
tpcv.bc_token = '01pbc-c2zfoyxQJbVGZiQYX6nJsLAu83vA-ynPiEWKA.';

// flag for brightcove player being fully initialized
tpcv.bc_init = false

	
// ---------------------------------------------------------------------------------------------
// -- Standard Video Properties

// this flag (load from page request) tells us if it's the initial page load, where we handle query string params different
tpcv.load_pg_req = true;

// current page for any resultset
tpcv.pg = 0;

// videos per page
tpcv.pp = 15;

// featured playlist ID
tpcv.fpid = 2652468001;

// playlist video resultset index
tpcv.vidx = 0;

// current search query
tpcv.s = null;

// currently playing video
tpcv.vid = 0;

// the slider playlist
tpcv.spid = 0;

// tells us if this is the video page
tpcv.vp = false;

// url prefix for video links
tpcv.lurl = '';

// ---------------------------------------------------------------------------------------------
// -- Video Functions
	

tpcv.video = function() {
	if (tpc.param('dbg','') == 'true') {
		tpcv.debug = true;
		console.log("Initializing javascript video page...");
	}
	tpcv.init_search();

	// determine if this is the video page or not. look for 'tampabay.com/video' in the url
	tpcv.vp = (document.location.href.indexOf('tampabay.com/video') != -1);

	if (tpcv.debug) {
		if (tpcv.vp) console.log("Currently on the video channel.");
		else console.log("Not on the video channel.");
	}
	
	// automatically perform a search based on the "p" parameter in the url, unless it's not there
	// ... just use the default playlist		
	if (tpcv.debug) console.log("Loading initial search...");
	tpcv.load_initial_search();
	
	if (tpcv.debug) console.log("Calling video player...");	
	tpcv.play();	
}
	
tpcv.play = function(argvid, argpid) {

	// -- SINGLE VIDEO PLAY LOGIC --
	// handle a VIDEO ID first in the play lineup. Look for the video ID as an argument to this
	// method, then url parameter.  If not found, move along to the playlist autoplay logic
	
	var _vid = -1;
	// if a "vid" is passed, that overrides everything. play the video
	if (argvid) {
		_vid = argvid;
	} else {
		// try to get the video id from the query string
		_vid = tpcv.get_vid();
	}
	
	if (_vid > 0) {
		if (tpcv.debug) console.log("Playing a video with ID: "+ _vid);
		tpc_v_p(_vid);
		return;
	} else {
		if (tpcv.debug) console.log("No valid video ID found. Aborting AUTOPLAY of video");
	}
	
  // -- PLAYLIST PLAY LOGIC --
	// At this point, no valid video id was found, so we'll need to load a playlist
	// based on first argument, and then url, and finally object property
	var _pid = -1;
	
	if (argpid) {
		if (tpcv.debug) console.log("Using playlist id from argument")
		_pid = argpid;
	} else {
		var _urlpid = tpc.param('p', '');
		if (_urlpid != '') {
			if (tpcv.debug) console.log("Using playlist from URL");
			_pid = _urlpid;
		} else {
			if (tpcv.debug) console.log("Falling back to default playlist");
			_pid = tpcv.fpid;
		}
	}
	
	// for Playlist Plays - select the correct video index (using argument pv: default is 0)
	tpcv.vidx = tpc.param('pv','0');
	
	tpcv.sendRequest('command=find_playlist_by_id&playlist_id=' + _pid, 'tpcv.handlePlayVideoFromPlaylist');
}

/*
 * Performs a search against the brightcove RESTful api. There are three types of searches:
 * 
 * 1. PID based (load results from a playlist)
 * 2. TAG based (load results from a brightcove tag search)
 * 3. TEXT based (load results from a brightcove text search)
 * 
 */
tpcv.search = function(q, clearSearch) {
	
	if (clearSearch === undefined)
		clearSearch = false;
		
	if (clearSearch) {
		if (tpcv.debug) console.log("Resetting search");
		tpcv.pg = 0;
		tpcv.vidx = 0;
		tpcv.s = null;
	} 
	
	if (tpcv.debug) {
		console.log("Search Properties: pg=" + tpcv.pg + ",vidx=" + tpcv.vidx + ",s=" + tpcv.s);
	}
		
	
	if (tpcv.debug) console.log("Performing a search with query: " + q);
	
	$('#videoList').html('<div class="playlistLoader">Loading<br /><img src="http://www.tampabay.com/universal/images/bc-loading-video.gif" alt="" border="" /></div>');
	
	q = (!q) ? '' : tpc.trim(q);
	
	if (q == tpcv.defst || q == '') {
		tpc_v_show_search_error('Please enter a valid search query');
	}
		
	tpcv.q = q;	
	tpcv.parseQuery();

	tpc_v_update_playlist_sidebar();
	
	
	if (tpcv.s.type == tpcv.PID_SEARCH) {
		if (tpcv.debug) console.log("This is a PLAYLIST Search for PID: "+ tpcv.s.pid);
		tpcv.sendRequest('command=find_playlist_by_id&playlist_id=' + tpcv.s.pid, 'tpcv.handleSearch');
	} else if (tpcv.s.type == tpcv.TAG_SEARCH) {		
		if (tpcv.debug) console.log("This is a TAG Search for TAG: "+ tpcv.s.tag);
		tpcv.sendRequest('command=find_videos_by_tags&and_tags=' + encodeURIComponent(tpcv.s.tag) + '&sort_by=MODIFIED_DATE&sort_order=DESC&get_item_count=true&page_size=' + tpcv.pp + '&page_number=' + tpcv.pg, 'tpcv.handleSearch');
	} else if (tpcv.s.type == tpcv.TEXT_SEARCH) {
		if (tpcv.debug) console.log("This is a TEXT Search for TEXT: " + tpcv.s.text);
		tpcv.sendRequest('command=find_videos_by_text&text=' + encodeURIComponent(tpcv.s.text) + '&sort_by=MODIFIED_DATE&sort_order=DESC&get_item_count=true&page_size=' + tpcv.pp + '&page_number=' + tpcv.pg, 'tpcv.handleSearch');
	} else {
		if (tpcv.debug) console.log("This is an unknown search type: " + tpcv.s.type);
	}
	
}

/*
 * Creates the video carousel
 */
tpcv.slider = function(pid, videoPage) {	

	if (videoPage == undefined)
		videoPage = false;

	if (pid == undefined || trim(pid) == '') {
		if (tpcv.debug) console.log("Defaulting slider playlist to featured playlist id");
		pid = tpcv.fpid;
	}

	if (tpcv.debug) console.log("Building the slider for playlist: "+ pid);
	tpcv.spid = pid;
	tpcv.sendRequest('command=find_playlist_by_id&playlist_id=' + pid, 'tpcv.handleSlider');
}

/* 
 * Performs a REST request to brightcove, and sends JSON data back to the callback function
 */
tpcv.sendRequest = function(cmd, callback) {
	var _request = 'http://api.brightcove.com/services/library?' + cmd + '&token=' + encodeURIComponent(tpcv.bc_token) + '&callback=' + callback
	
	if (tpcv.debug) { console.log("Sending REST request to brightcove: " + _request); }
	
	jsonObj = new tpcjsonreq(_request);
	jsonObj.buildScriptTag();
	jsonObj.addScriptTag();	
}

/* 
 * Use a query to determine the type of search
 *
 * There are three types of searches to perform:
 * 
 * 1: Playlist Search  (pid:999)
 * 2: Text based search (plain text)
 * 3: Tag based search (tag:999,999,999)
 *   
 */
tpcv.parseQuery = function() {
	
	var searchObj = [];
	
	/*
	 * No query is defined, so assume this is a playlist search and use the default playlist
	 */
	if (!tpcv.q) {
		searchObj.type = tpcv.PID_SEARCH;
		searchObj.pid  = tpcv.fpid;
		tpcv.s = searchObj;
		return;
	}
	
	var _query = tpc.trim(tpcv.q);
	
	/*
	 * If the query starts with "pid:" we can assume a playlist search
	 */
	var pidRegExp = /pid\:(\d+)/i;
	var reResult  = pidRegExp.exec(_query);
	if (reResult != null) {
		searchObj.type = tpcv.PID_SEARCH;
		searchObj.pid  = reResult[1];
		tpcv.s = searchObj;
		return;
	}
	
	/*
	 * If the query starts with "tag:" we can assume a tag search 
	 */
	var tagRegExp = /tag:(.*)/i;
	reResult = tagRegExp.exec(_query);
	if (reResult != null) {
		searchObj.type = tpcv.TAG_SEARCH;
		searchObj.tag = reResult[1].replace('/\s/',',');
		tpcv.s = searchObj;
		return;
	}
	
	/*
	 * At this point, we can assume a basic text search.
	 */
	searchObj.type = tpcv.TEXT_SEARCH;
	searchObj.text = _query;	
	tpcv.s = searchObj;
}


//---------------------------------------------------------------------------------------------
//-- Static Callback Handlers

tpcv.handlePlayVideoFromPlaylist = function(json) {	
	if (tpcv.debug) console.log("Got JSON response");

	// TODO: json data error handling
	var videos = json['videos'];
	tpc_v_p(videos[tpcv.vidx]['id']);
}

tpcv.handleSearch = function(json) {
	if (tpcv.debug) console.log("Got json response for playlist search: " + json.length);
	
	if (json.error) {
		alert("ERROR: "+ json.error);
		return;
	}
	
	// TODO: json data error handling
	var v = (json['videos']) ? json['videos'] : json['items'];

	if (tpcv.debug) console.log("Total items found: " + v.length);
	
	if (v.length == 0) {
		$('#videoList').html('<div class="videos-err">No videos found.</div>');
	} else {
		
		var _contentArea = $('<div/>').attr('class','video-container-outer').append($('<div/>').attr('class','video-container-inner'));
		
		// video count
		var vc = 0;  
				
		// total videos
		var tv = (tpcv.s.type == tpcv.PID_SEARCH) ? v.length : json['total_count'];
		
		// total pages
		var tp = Math.floor(tv / tpcv.pp);
		if (tv % tpcv.pp > 0) tp++;

    // currently playing video
    tpcv.vid = tpcv.get_vid();
		
		// change the current page to accomodate for the video idx if this is a PID search
		if (tpcv.s.type == tpcv.PID_SEARCH) {
		
		  // make sure the video index isn't greater than the number of videos in our collection
		  if (tpcv.vidx > tv) {
		    tpcv.vidx = 0;
		  } 


      // the video index is set, but not the video parameter. go ahead and assign the variable      
      if (tpcv.vid == '' || tpcv.vid == 0) {
        for (var i = 0; i < v.length; i++) {          
          if (i == tpcv.vidx) {
            tpcv.vid = v[i].id;
          }
        }
      } else if (tpcv.vid != '') {
        for (var i = 0; i < v.length; i++) {
          if (v[i].id == tpcv.vid) {
            tpcv.vidx = i;
          }
        }
      }
  
      if (tpcv.load_pg_req) {
  		  // set the current viewing page to the page that this video would fall under
        if (tpcv.vidx > 0) {
          tpcv.pg = Math.floor(tpcv.vidx / tpcv.pp);
        }
        
        tpcv.load_pg_req = false;
      }      
		}
		
		// create the navigation
		var _nav = tpcv.build_nav(tp);
		
		// append the title
		var _resultTitle = tpcv.build_result_title(json);
		_contentArea.append(
			$('<div/>').attr('class','videoResultTitleBar').append(
				$('<div/>').attr('class','videoResultTitleBarText').html(_resultTitle)
			).append(
				_nav
			)
		).append(	$('<div/>').attr('class','clear')	);
		
		var _startAt = (tpcv.s.type == tpcv.PID_SEARCH) ? (tpcv.pg * tpcv.pp) : 0;
		
		for (var i = _startAt; i < v.length; i++) {
			vc++;			
		
			var _link = tpcv.build_video_link(v[i]);
			
			var _vdiv = $('<div/>').attr('class','videoElement').append(
				$('<a/>').attr('href',_link).append($('<img/>').attr('height','90').attr('width','120').attr('src',v[i].thumbnailURL))
			).append(
				$('<br/>')
			).append(
				$('<a/>').attr('href',_link).html(v[i].name + ' (' + tpc_v_format_time(v[i].length) + ')')
			);
			
			if (tpcv.vid == v[i].id)
			 _vdiv.addClass('nowplaying');
		
			_contentArea.append(_vdiv);
			
			if (vc == tpcv.pp)
				break;
		}		
		
		// clear the div and append the entire search result
		$('#videoList').html('');
		$('#videoList').append(_contentArea);
		
		tpcv.firstLoad = false;
	}	
}


/*
 * Creates a link for a video based on the type of search.
 */
tpcv.build_video_link = function(v) {

  var l = '?bctid=' + v.id;

	// error handling for null search objects
  if (tpcv.s == null) {
  	if (tpcv.spid != undefined && trim(tpcv.spid) != '') {
		l += '&p=' + tpcv.spid;
	}
	return l;
  }
  
  if (tpcv.s.type == tpcv.PID_SEARCH) {
    if (tpcv.s.pid) {
      l += '&p=' + tpcv.s.pid;
    }
  }
  
  else if (tpcv.s.type == tpcv.TAG_SEARCH) {
    l += '&q=tag:' + encodeURIComponent(tpcv.s.tag);
    l += '&pg=' + tpcv.pg;
  }
  
  else if (tpcv.s.type == tpcv.TEXT_SEARCH) {
    l += '&q=' + encodeURIComponent(tpcv.s.text);
    l += '&pg=' + tpcv.pg;
  }
  
  if (tpcv.lurl != '') {
  	l = tpcv.lurl + l;
  }

  return l;			
}

/*
 * Creates the nav for our search result page
 */
tpcv.build_nav = function(tp) {
	var cp = tpcv.pg + 1;
	if (tpcv.debug) console.log("Building nav. Current page: " + cp + ". Total pages: " + tp);

	var _nav = $('<div/>').attr('class','videoResultTitleBarPagination');
	
	// create previous page
	if (tpcv.pg > 0) {
		_nav.append(
			$('<span/>').html('Previous').attr('class', 'video-result-nav-link').bind('click',function() {
				--tpcv.pg;
				tpcv.search(tpcv.q, false);
			})
		).append(
			" | "
		);
	}
	
	// create the x of y page
	if (tp > 1)
		_nav.append("Page " + cp + " of " + tp);
	else
		_nav.append("Page 1");
	
	// create the "next" pge
	if (cp < tp) {
		_nav.append(
			" | "
		).append(
			$('<span/>').html('Next').attr('class', 'video-result-nav-link').bind('click',function() {
				++tpcv.pg;
				tpcv.search(tpcv.q, false);
			})
		);
	}
	
	return _nav;
}

/*
 * Gets the video ID from the URL. this is useful since we have two parameters specifying
 * a video on our site (bctid and v)
 */
tpcv.get_vid = function() {
		var _bctid = tpc.param('bctid', '');
		if (_bctid != '') {
			return _bctid;
		} 
		
		var _vid = tpc.param('v','');
		if (_vid != '')
		  return _vid;
		  
		return 0;
}

/*
 * Examines the search to see what the result box title should be
 * There is a case for playlist, tag and text search
 */
tpcv.build_result_title = function(json) {

	if (tpcv.s.type == tpcv.PID_SEARCH) {
		return (json['name'] === undefined) ?
			"Playlist Result" :
 			json['name'] + " (" + json['videos'].length + ")";
	}
	
	if (tpcv.s.type == tpcv.TAG_SEARCH) {
		return (json['total_count'] === undefined) ?
			"Videos tagged " + tpcv.s.tags :
			"Found	 " + json['total_count'] + " video" + ((json['total_count'] != 1) ? "s" : "") + " tagged " + tpcv.s.tag;
	}

	if (tpcv.s.type == tpcv.TEXT_SEARCH) {
		return (json['total_count'] === undefined) ?
			tpc.trim(tpcv.s.text) :
			"Found " + json['total_count'] + " result" + ((json['total_count'] != 1) ? "s" : "") + " for " + tpc.trim(tpcv.s.text);
	}

	return "Results";
}

/*
 * Update styling on playlist sidebar
 */
function tpc_v_update_playlist_sidebar() {
	
	if (tpcv.debug) console.log("Removing all vid-active classes from sidebar");
	$.each($('#videoLineups div'), function() {
		$(this).removeClass('vid-active');		
	});
	
	if (tpcv.s.type == tpcv.PID_SEARCH) {
		if (tpcv.debug) console.log("Attempting to add class for playlist ID=" + tpcv.s.pid);
		$('#spl' + tpcv.s.pid).addClass('vid-active');
	}
	
}


/*
 * This is the first search on page laod that populates the result set area. This
 * is dependent on the query string.
 *
 * if 'p' -> load playlist search
 * if 'q' -> load tag search if tag:, load text search if text:
 * else   -> load default playlist search
 */
tpcv.load_initial_search = function() {

  var _p = tpc.param('p', '');
  var _q = tpc.param('q', '');
  var _pg = tpc.param('pg', '0');
  
  if (tpcv.debug) { console.log ("Determining which search to load initially: p=" + _p + ",q=" + _q + ",pg=" + _pg); }
  
  // run a playlist search
  if (_p != '') {
    tpcv.search('pid:' + _p);
  } 
  
  // run a tag or text based search
  else if (_q != '') {    
    tpcv.pg = parseInt(_pg);
    tpcv.search(decodeURIComponent(_q));
  }
  
  // just load the default playlist
  else {
    tpcv.search('pid:' + tpcv.fpid);
  }
}
	

tpcv.handleSlider = function(json) {
	if (tpcv.debug) console.log("Got json response for slider handler: " + json.length);
	
	if (json.error) {
		tpcv.handleError(json.error);
		return;
	}	
	
	$('#bcSidebarTitle').html(json.name);

	// determine if this is the video page or not. look for 'tampabay.com/video' in the url
	// even though this is done in the "init" method, that might not be called on an article or
	// channel page
	tpcv.vp = (document.location.href.indexOf('tampabay.com/video') != -1);
	
	var v = (json['videos']) ? json['videos'] : json['items'];
	
	if (tpcv.debug) console.log("Slider will load with " + v.length + " videos.");
	
	var vc = 1;
	var _vid = tpcv.get_vid();
	var _fpos = -1;
	
	// create the belt container
	var belt = $('<div/>').attr('class', 'belt');
	for (var i = 0; i < v.length; i++) {
	
		if (v[i].id == _vid)
			_fpos = vc;
	
		var l = '/video/' + tpcv.build_video_link(v[i]);

		var _img = $('<img/>').attr('src', v[i].thumbnailURL);
		_img.attr('width','80');
		_img.attr('height', '60');
		_img.attr('border', '0');
	
		belt.append(
			$('<div/>').attr('class','panel').append(
				$('<a/>').attr('href', l).append(
					_img
				)
			).append(
				$('<br/>')
			).append(
				$('<a/>').attr('href', l).attr('class','bcTitleLinkText').html(v[i].name)
			)	
		);
		
		if (tpcv.debug) console.log("Appended video ID=" + v[i].id + " to the slider at position: " + vc);
		
		vc++;
	}
	
	$('#bcSidebarPlaylist').html(belt);
	
	// set up the slider
	stepcarousel.setup({
		galleryid: 'bcSidebarPlaylist', //id of carousel DIV
		beltclass: 'belt', //class of inner "belt" DIV containing all the panel DIVs
		panelclass: 'panel', //class of panel DIVs each holding content
		autostep: {enable:(!tpcv.vp), moveby:1, pause:3000},
		panelbehavior: {speed:500, wraparound:false, persist:true},
		defaultbuttons: {enable: false, moveby: 1, leftnav: ['http://www.tampabay.com/universal/images/video-list-left.png', 0, 30], rightnav: ['http://www.tampabay.com/universal/images/video-list-right.png', -24, 30]},
		statusvars: ['BCstatusA', 'BCstatusB', 'BCstatusC'], //register 3 variables that contain current panel (start), current panel (last), and total panels
		contenttype: ['inline'] //content setting ['inline'] or ['external', 'path_to_external_file']
	});		
	
	if (_fpos > 0) {
		if (tpcv.debug) console.log("Stepping to featured video at position: " + _fpos);
		stepcarousel.stepTo('bcSidebarPlaylist', _fpos);
	}
	
	
}

tpcv.handleError = function(msg) {
	// TODO: Find a better way to handle error messages
	if (tpcv.debug) console.log("ERROR: " + msg);
}

//---------------------------------------------------------------------------------------------
//-- Static Video Functions

function tpc_v_p(vid) {
	if (!tpcv.bc_init) {
		if (tpcv.debug) console.log("Brightcove is not yet initialized. Waiting...");
		setTimeout("tpc_v_p("+ vid +")", 250);
	} else {		
		tpc_v_modCon.getVideoAsynch(vid);
		if (tpcv.debug) console.log("Video ID="+ vid +" queued up in brightcove player");
	}
}

/*
 * Formats a set of "milliseconds" into a readable time
 */
function tpc_v_format_time(len) {
	var t_secs = Math.round(len/1000);
	var mins = Math.floor(t_secs/60);
	var secs = t_secs - (mins*60);
	if (secs == 0) return mins + ':' + secs + "0";  
	else if (secs < 10) return mins + ':0' + secs; 
	else return mins + ':' + secs;
}

function tpc_v_show_search_error(msg) {
	$('#vc-search-msg').html(msg).fadeIn('slow');
	setTimeout("tpc_v_hide_search_error()", 7500);
}

function tpc_v_hide_search_error() {
	$('#vc-search-msg').fadeOut('slow');
}

/*
 * Initializes the search bar
 */
tpcv.init_search = function() {	
	
	$('#vc-search').val(tpcv.defst);
	
	$('#vc-search').bind('focus', function(e) {
		if ($('#vc-search').val() == tpcv.defst)
			$('#vc-search').val('');
	}).bind('blur', function(e) {
		if (tpc.trim($('#vc-search').val()) == '')
			$('#vc-search').val(tpcv.defst);
	}).bind('keydown', function(e) {
		if (e.keyCode == 13) 
			tpcv.search($('#vc-search').val(), true);
	});
	
	
	$('#vc-go').bind("click", function(e) {
		tpcv.search($('#vc-search').val(), true);
	});
	
	$('#vc-search-msg').bind("click", function(e) { tpc_v_hide_search_error() });
	
	// set the search value if a "q" is in the url
	var _q = tpc.param('q','');
	if (_q != '') {
	 $('#vc-search').val(decodeURIComponent(_q));
	}
	
}