// jQuery
jq(function(){
	
	initialize_defaults();
	
	if (jq('#quick_tabs').length) {    
	  jq('#quick_tabs').each(function () { 
			$triggers = jq(this).find('a');
	    panelIds = $triggers.map(function() {return this.hash}).get().join(",");
			$panels = jq(panelIds);
      $panels.hide();

			$triggers.click(function(event) {
        var trigger  = this,
        		$trigger = jq(this);
						
				Cookie.set('panel', this.hash);
        if ( $trigger.is('.active') )
          return false;

        $triggers.removeClass('active');
        $trigger.addClass('active');
				
				$panels.hide().filter(trigger.hash).show();
				
				return false;
			});
			if ( Cookie.get('panel') )
				$triggers.filter('[hash=' + Cookie.get('panel') + ']').click();
			else
	      $triggers.filter(window.location.hash ? '[hash=' + window.location.hash + ']' : ':eq(0)').click();
		});
	}		
});

function initialize_defaults() {
	Cookie = {
	  // get cookie value
	  get: function(name) {
	    var name  = name + '=', 
	        start = document.cookie.indexOf(name), 
	        value = null;

	    if ( start > -1 ) { 
	      var end = document.cookie.indexOf(';', start);

	      if ( end == -1 ) 
	        end = document.cookie.length; 

	      value = decodeURIComponent(document.cookie.substring(start + name.length, end)); 
	    } 

	    return value; 
	  },

	  // set cookie
	  // expires => [Object Date]
	  set: function(name, value, yrs_from_now) {
	    var text = name + '=' + encodeURIComponent(value) + '; path=/';

	    if ( typeof yrs_from_now == 'number' ) {
	      var expires = new Date();

	  	  expires.setFullYear(expires.getFullYear() + yrs_from_now);
	      text += '; expires=' + expires.toGMTString(); 
	    }

	    document.cookie = text;
	  },

	  unset: function(name) {
	    this.set(name, '', new Date(0));
	  }
	}

	// Array.indexOf [Mozilla version] added for IE
	if (!Array.prototype.indexOf) {
	  Array.prototype.indexOf = function(elt /*, from*/) {
	    var len = this.length;
	    var from = Number(arguments[1]) || 0;
	    from = (from < 0) ? Math.ceil(from) : Math.floor(from);

	    if (from < 0)
	      from += len;

	    for (; from < len; from++) {
	      if (from in this && this[from] === elt)
	        return from;
	    }

	    return -1;
	  };
	}
}

function set_video_toggle(){
	jq('#video_data').remove();
  jq('#video_toggle').click(function(){
		vid_toggle();
		return false;
	});	
}

// fired by jw-player after loading
// offsite_video, article_video overwrite this
function playerReady(playa) {
  var player = jq('#' + playa.id);
  
  playa = player.get(0);
  playa.addViewListener('PLAY', 'update_video_plays');
}

function update_video_plays(video) {
  var playa = jq('#' + video.id),
      loc   = start_path() + 'update_video_plays/' + video.id.replace('video_', '');
      
  jq.get(loc);
  playa.get(0).removeViewListener('PLAY', 'update_video_plays');
}

function start_path() {
  var loc = location.pathname.match(/^\/[\w-]+?\//);
  
  if ( loc == '/experts/' ) 
    return location.pathname.match(/^\/experts\/[\w-]+?\//);
  else
    return loc;
}

/* initVideo: video obj
 * {
 *   :url           => vid.url,
 *   :file_type     => vid.file_type,
 *   :size          => vid.size,
 *   :klass         => vid.class.to_s,
 *   :id            => vid.id,
 *   :preview_photo => vid.preview_photo ? vid.preview_photo.image_path : ''
 * }
 */
function initVideo(video, i, callback) {
	var target    = 'video_' + ++i,
	    size      = size_values(video.size, video.klass),
	    swf       = '/flash/player.swf',
	    flashvars = { file: video.url, width: size.w, height: size.h },
	    params    = { allowScriptAccess: 'always', allowFullScreen: 'true', wmode: 'transparent', scale: 'noscale', menu: 'false' },
	    attrs     = { id: 'video_' + video.id, name: 'video_' + video.id, 'class': 'vid' };
	    
	if ( video.preview_photo ) 
	  flashvars.image = video.preview_photo;
	
	swfobject.embedSWF(swf, target, size.w, size.h, '9', false, flashvars, params, attrs, callback);
}

function size_values(ratio, type) {
  if ( ratio == '4:3' || type == 'ArticleVideo' )
    return { 'w': 320, 'h': 260 };
  else if ( ratio == '16:9' ) 
    return { 'w': 384, 'h': 236 };
}

function vid_toggle() {
	var collection = jq('#videobox'),
	    box_height = collection.outerHeight();
	    
	if ( box_height > 0 ) {
	  collection.animate({ height: 0 }, 600, 'easeInOutQuint');
    jq('#video_toggle').html('show video');
	} else {
	  collection.animate({ height: 278 }, 600, 'easeInOutQuint');
    jq('#video_toggle').html('hide video');
	}
}

// prototype
Event.observe(document, 'dom:loaded', init);

function init() {	
	if (!location.pathname.startsWith('/admin'))
		flashinit();
	observer();
	radioResponder();
	var detail_main = $$('.detail_main');
	if(detail_main != "") {
		sizeToFit(detail_main);
	}
	var detail_logo = $$('.detail_logo');
	if(detail_logo != "") {
		sizeToFit(detail_logo);
	}
	var gallery = $('photo_gallery');
	if (gallery) {
		initGlider();
	}
}
 
function sizeToFit(image) {
	maxW = 240;
	w = image.first().getWidth();
	h = image.first().getHeight();
	if(w>maxW) {
		f=1-((w - maxW) / w);
		image.first().width = w * f;
	    image.first().height = h * f;
	}
}

function flashinit() {
	var flashvars = {};
	var params = {allowScriptAccess: "always", wmode: "transparent", scale: "noscale", menu: "false"};
	var attributes = { id: "map", name: "map" };
	swfobject.embedSWF("/flash/map.swf", "flash_map", "270", "216", "8", false, flashvars, params, attributes);
}

function observer() {   
	var searchGroup = $('search_radios');
	if (searchGroup)
		searchGroup.select('li input').invoke('observe', 'click', radioResponder);
}

function radioResponder() {
	var value = jq('#state').val(),
	    search_type = jq('#search_radios li input:checked').val();
  update_states(search_type, value);
}

function update_states(search_type, value) {
	if (value == "") {
  	jq('#state').html("<option value=''>-- </option>" + jq.map(["DC", "DE", "MD", "NJ", "PA", "VA"], function(obj) { return "<option value='" + obj + "'>" + obj + "</option>" }).join(''));
  	jq('#county').html("<option value=''>-- </option>");
	}
}

//observes manual change to state -- updates counties and send to flash
function observe_state(value, controller) {
	if(typeof controller != "undefined") {
	new Ajax.Updater('county', '/'+ controller +'/update_counties', {asynchronous:true, evalScripts:true, parameters:'state=' + value +  '&authenticity_token=' + encodeURIComponent(AUTH_TOKEN)});
	updateFlash(value);
	}
	if ( !jq('#search_radios input:checked').length )
		jq('#search_radios input[value=homecare]').click()
}
	
//observes programatic change to state -- updates counties
function observe_flash_state(value, controller) {
	if(typeof controller != "undefined") {
	new Ajax.Updater('county', '/'+ controller +'/update_counties', {asynchronous:true, evalScripts:true, parameters:'state=' + value +  '&authenticity_token=' + encodeURIComponent(AUTH_TOKEN)});
	}
	if ( !jq('#search_radios input:checked').length )
		jq('#search_radios input[value=homecare]').click()
}

//sends state to flash
function updateFlash(value) {
	var swf = $("map");
	if (swf) {
		swf.updateFlash(value);
	}
}

//flash calls this to check for search type
function check_search_type() {
	if (controller != null) {
		return true;
	}
}

//flash calls this to set the state dropdown and trigger update counties
function set_state_id(state_id) {
   	var selectObj = $('state');
   	for (var i = 0; i < selectObj.length; i++) {
      	if(selectObj.options[i].value == state_id)
      		selectObj.selectedIndex = i;   
   	}
   	observe_flash_state(state_id, controller);
}

function initGlider() { 
  var photo_glider = new Glider('photo_gallery', {duration:0.3});    
  $('photo_previous').observe('click', function(event){
   photo_glider.previous();
   event.preventDefault(); 
  });
  $('photo_next').observe('click', function(event){
   photo_glider.next();
   event.preventDefault(); 
  });
}

function pro_toggle(value) {
	if(value == 'individual') {
		if ($('order-use').getStyle('display') == 'none') {
			Effect.toggle('order-use', 'blind', {duration: .5});
			Effect.toggle('order-quantity', 'blind', {duration: .5});
			Effect.toggle('order-sub', 'blind', {duration: .5});
			Effect.toggle('order-title', 'blind', {duration: .5});
			Effect.toggle('order-org', 'blind', {duration: .5});
			Effect.toggle('order-fax', 'blind', {duration: .5});
			Effect.toggle('ad-info', 'blind', {duration: .5});
		};
	}
	else {
		if ($('order-use').getStyle('display') != 'none') {
			Effect.toggle('order-use', 'blind', {duration: .5});
			Effect.toggle('order-quantity', 'blind', {duration: .5});
			Effect.toggle('order-sub', 'blind', {duration: .5});
			Effect.toggle('order-title', 'blind', {duration: .5});
			Effect.toggle('order-org', 'blind', {duration: .5});
			Effect.toggle('order-fax', 'blind', {duration: .5});
			Effect.toggle('ad-info', 'blind', {duration: .5});
		};
	}
}


function limitText(limitField, limitNum, countField) {
  if (limitField.value.length >= limitNum) {
    limitField.value = limitField.value.substring(0, limitNum);
    countField.value = 0;
  } else {
    countField.value = limitNum - limitField.value.length;
  }
}



