function checkFirebug(){
    var haveFB=(typeof window.console != "undefined" && window.console['firebug']);
    if (!haveFB) {
        var names=["log","debug","info","warn","error","assert","dir","dirxml","group","groupEnd","time","timeEnd","count","trace","profile","profileEnd"];
        window.console={}; for(var i=0;i<names.length;++i){window.console[names[i]]=function(){}}
        if (location.search.indexOf("firebug=t") != -1) {
            var q=document.createElement('script');
            q.setAttribute('src', '/_js/lib/firebug-lite-1.2-compressed.js');
            document.getElementsByTagName('head')[0].appendChild(q);
        }
    }
}
checkFirebug();

document.observe('dom:loaded', function(){
    observeTextPrompts();
	observeSignupForm();
    triggerPersonalize();
	observeSearchForm();
	checkForPreview();
	quizPopupLink();
	favorite_button_generator();
	latest_c_block();
});

function isLoggedIn() {
	var loggedIn = getCookie('is_logged_in');
    return (loggedIn && loggedIn != '0');
}

function triggerPersonalize() {
	if(isLoggedIn()) {
		toggleLoggedInContent(true);
		personalizeThePage(isLoggedIn());
	}else{
		toggleLoggedInContent(false);
	}
}

Event.observe(window, 'load', function() {
    // load em
	reloadAds();

	// Hey there! This is a soul-sucking patch for an IE float bug. Weeeeee!
	if(Prototype.Browser.IE){
		var mainContent, sidebar = null;
		if(mainContent = $$('#content .main')[0]){
			if(sidebar = $$('.sidebar')[0]){
				sidebar.style.minHeight = mainContent.getDimensions().height+'px';
			}
		}
	}

});


// Set or drop cookie
function setCookie(cName, value, age) {
    var dc = cName + "=";
    if (typeof value != "undefined") {
        dc += value + "; path=/";
        if (typeof age != "undefined") {
            if (age != -1) {
                var d = new Date();
                d.setTime(d.getTime()+age*1000);
                dc += "; Expires=" + d.toUTCString();
            }
        }
    } else {
        dc += "; path=/; Expires=" + new Date(0).toUTCString();
    }
    document.cookie = dc;
}

// Get the value of the cookie with cName, return null if it does not exist
function getCookie(cName) {
    var c = null;
    var ac = document.cookie;
    var start = ac.indexOf(cName+"=");
    if (start >= 0) {
        start += cName.length + 1;
        var end = ac.indexOf(";", start);
        if (end == -1) end = ac.length;
        c = ac.substring(start, end);
    }
    return c;
}


function observeTextPrompts() {
    $$('.textPrompt').each(function(field, index){
        var prompt = field.value;
        field.observe('focus', function(){
            if(field.value == prompt){
                field.value = "";
            }
        }.bind(this));
        field.observe('blur', function(){
            if(field.value.strip() == ''){
                field.value = prompt;
            }
        }.bind(this));
    });
}

function observeSignupForm(){
	if($('newsletter_signup_form')){
		// Observe the form has a valid email
		$('newsletter_signup_form').onsubmit = function(){
			if(this.select('.signup')[0].value.strip().match(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i)){
				return true;
			}else{
				alert("Please enter a valid email address");
				return false;
			}
		}
	}	
}

function observeSearchForm() {
	if($('search_form')) {
		$('search_form').onsubmit = function() {
			var elem = this.select('#search')[0];
			if(elem.value.strip() == '' || elem.value.strip() == 'Search Modelinia' || elem.value.strip() == 'Search for..') {
				alert("Please enter a search term.");
				return false;
			} else {
				return true;
			}
		}
	}

}

function captchaClickHandler(evt){
	// get the element that fired the event
	var ele = Event.element(evt);

	// make sure we've got a direct decendant of the captcha ul
	while(ele.up().id != "captcha-options"){ ele = ele.up(); }

	// get the numeral on the end of our id string
	var id = ele.id.substr(ele.id.length-1);
	
	var captcha_value = $('captcha_field').value;
	var captcha_values = [captcha_value.charAt(0), captcha_value.charAt(1)];

	// if already selected, uncheck it
	if (captcha_value.indexOf(id) > -1) {
		for (var i=0; i < captcha_values.length; i++) {
			if (id == captcha_values[i]) {
				ele.removeClassName("selected");
				captcha_values[i] = '';
			}
		}
	} else if (captcha_value.length == 2) {
		return false;
	} else {
		if (captcha_values[0] == '') {
			captcha_values[0] = id;
		} else if (captcha_values[1] == '') {
			captcha_values[1] = id;
		}
		ele.addClassName("selected");
	}

	// finally store our captcha values back in the hidden element as comma seperated values
	$('captcha_field').value = captcha_values.join('');
	return false;
}

function add_favorite(type, id){
	url = "/dashboard/add_favorite";
	pars = "&id="+id+"&type="+type;
	$('favorite-button').innerHTML='<span class="favorite_it_communicating"></span>';
	var myAjax = new Ajax.Updater(
		'favorite-button',
		url,
		{method: 'post', parameters: pars}
		);
}

function switch_model_sorting(type_on) {
	var type_off= '';
	if ( type_on == 'models_by_name' ) {
		type_off= 'models_by_campaign';
	}
	else if ( type_on == 'models_by_campaign' ) {
		type_off= 'models_by_name';
	}
	else {
		return;
	}
	var type_on_li= type_on + '_li';

	var type_off_li= type_off + '_li';
	document.getElementById(type_on).style.display= 'block';
	document.getElementById(type_on_li).className= 'selected';
	document.getElementById(type_off).style.display= 'None';
	document.getElementById(type_off_li).className= '';
}


function card_select_toggle( card_owner , card_id ) {
	card_id= parseInt(card_id);

	var node_stash= null;
	var node_stash_name= null;
	if ( card_owner == 'self' ) {
		node_stash= $('cards_self');
		node_stash_name= 'cards_self';
	}
	else if ( card_owner == 'other' ) {
		node_stash= $('cards_other');
		node_stash_name= 'cards_other';
	}
	if ( !node_stash ) { alert('Error'); }
	
	var selected_cards_as_string= Form.Element.getValue(node_stash_name);
	var selected_cards= selected_cards_as_string.split(':');
	
	var node_card= $( 'card_' + card_id );

	var card_already_selected= false;
	for ( x in selected_cards ) {
		var already_selected_card_id= parseInt(selected_cards[x]);
		if ( already_selected_card_id == card_id ) {
			card_already_selected = true;
		}
	}
	
	if ( ! card_already_selected ) {
		selected_cards.push( card_id );
		Element.addClassName( node_card , 'selected' );
	}
	else {
		selected_cards= selected_cards.without(card_id);
		Element.removeClassName( node_card , 'selected' );
	}

	selected_cards_as_string= selected_cards.join(':');
	Form.Element.setValue( node_stash_name , selected_cards_as_string );
}

function jump_to_model(item) {
	if (item.selectedIndex > 0) {
		document.location.href = item.options[item.selectedIndex].value;
	}
}

// Looks for any ads on the page and replaces them w/ iFrames 
// so we can refresh the adspace as needed
function reloadAds(){
	
	var ord = new Date().getTime();

	// adFrameOrScript might be a <script> tag, or an iFrame if we've already replaced.
	var adScripts = $$('[rel="dartscript"]');
//    console.debug("adscripts", adScripts);
	
	for(var index=0;index<adScripts.length;index++){
		var adFrameOrScript = adScripts[index];
		var adBlock = adFrameOrScript.parentNode;
		var adImage = null;
		var adId = 'dynamicAd'+index;

		// Get ad URL and store in the adBlock for future use
		var oldURL = null;
		if(adBlock.getAttribute('oldurl')){
			oldURL = adBlock.getAttribute('oldurl');
		}else{
			oldURL = adFrameOrScript.getAttribute('src');
			adBlock.setAttribute('oldurl', oldURL);			
		}
        var result = oldURL.match(/sz=(\d+)x(\d+)/);
        var adDimensions = { width: result[1]+'px', height: result[2]+'px' }

		// Update the URL w/ a new timestamp
		var newURL = oldURL.replace(/ord\=\d+/, 'ord='+ord);
		
		// If we havent already replaced the ad w/ an iFrame, do so now
		if(!window.frames[adId]){	
			var adFrame = document.createElement('iframe');

			adFrame.setAttribute('style', 'border:none;width:'+adDimensions.width+';height:'+adDimensions.height);
			adFrame.setAttribute('width', adDimensions.width);
			adFrame.setAttribute('height', adDimensions.height);
			adFrame.setAttribute('noresize', "noresize");
			adFrame.setAttribute('frameborder',"0");
			adFrame.setAttribute('frameBorder',"0"); // FUCKING IE!
			adFrame.setAttribute('border',"0");
			adFrame.setAttribute('cellspacing',"0"); 
			adFrame.setAttribute('scrolling',"no"); 
			adFrame.setAttribute('marginwidth',"0");
			adFrame.setAttribute('marginheight',"0");
			adFrame.setAttribute('class', 'adFrame');
			adFrame.setAttribute('rel', 'dartscript');
			adFrame.setAttribute('id', adId);
			adFrame.setAttribute('name', adId);

            adBlock.setAttribute('id', 'adblock_'+adId);
			adBlock.innerHTML = '';
			adBlock.appendChild(adFrame);

		}
		
		// Markup for iFrame
		var markup = '<html><head><style>body,html{background-color:transparent;padding:0;margin:0;}</style>' +
		             '<body scroll="no"><script src="'+newURL+'" type="text/javascript"></script>' +
                     '<script class="checkAd" type="text/javascript">window.parent.checkAd("'+adId+'");</script></body></html>';
		//var markup = '<html><head><style>body,html{background-color:transparent;padding:0;margin:0;}</style><body scroll="no"><script src="/_js/test.js" type="text/javascript"></script></body></html>';
		// Write the new document to the iFrame
		var iFrameDoc = window.frames[adId].document;
		iFrameDoc.open();
		iFrameDoc.write(markup);
		if(!Prototype.Browser.IE){ // Dont close the doc in IE! This makes IE cry. Boooo hooo!	
			iFrameDoc.close(); 
		}

		// Profit!
	}
}

// Check the iframe document to see if there is an ad.  If so display it.
function checkAd(adId) {
    var iFrameDoc = window.frames[adId].document;
    var scripts = iFrameDoc.getElementsByTagName('script');
    if (scripts.length == 0) {
        return;
    }
    var script = scripts[0];  // The dart script
    if (script.readyState) {  // IE - all others block downloads while a script is downloading
        script.onreadystatechange = function() {
            if (script.readyState == "loaded" || script.readyState == "complete") {
                script.onreadystatechange = null;
                checkAd2(iFrameDoc, adId);
            }
        };
        return;
    }
    checkAd2(iFrameDoc, adId);
}

function checkAd2(iFrameDoc, adId) {
//    var bodyc = iFrameDoc.getElementsByTagName('body')[0].childNodes;
//    for (i=0; i< bodyc.length; i++) { console.debug(i, bodyc[i]) }

    var imgs = iFrameDoc.getElementsByTagName('img');
    if (imgs.length > 0) {
        if (imgs[0].src.indexOf("817-grey.gif") >= 0) {
            return;
        }
    }

    // Turn on ad
    var adDiv = document.getElementById('adblock_'+adId);
    if (adDiv && adDiv.parentNode) {
        adDiv = adDiv.parentNode;
//        console.debug("turn it on!", adDiv);
        adDiv.style.display = "block";
    }

    // TODO - remove the checkAd script
}

/* FLASH INTERFACE */

// Add any functions that flash might call in here.
var FlashEvents = {
	// A counter for the number of slides viewed.
	_slidesViewed : 0, 

	// Rotate ads every N slide views.
	_SLIDES_AD_FREQUENCY : 3, 

	// Fired every time a quiz question is answered in flash
	quizQuestionAnswered : function(){ 
		reloadAds(); return false;
	},

	// Fired every time a slide is viewed in flash
	slideViewed : function(){

		this._slidesViewed++;
		if(this._slidesViewed % this._SLIDES_AD_FREQUENCY == 0){
//            console.log("slideshow page refresh");
			reloadAds();
            window.pageTracker._trackEvent("Ad", "slideshow page refresh", window.location.pathname);
		}

		return false;
	}
};



// for dart
ord = Math.ceil(Math.random()*100000000000);

/* LOGGED IN CONTENT */

// Shows logged in, or logged out content, depending upon the cookie
// NOTE: This assumes all logged in contents is display:block, not inline
function toggleLoggedInContent(show){	
	$$('.logged_out').each(function(element, index){
		show ? element.hide() : element.style.display = 'block';
	}.bind(this));
	$$('.logged_in').each(function(element, index){
		show ? element.style.display = 'block' : element.hide();
	}.bind(this));
}

// Adds user ID to the embed code. And anything else we want to add. 
function personalizeThePage(userId){
	$$('.video_sharing_embed').each(function(element, index){
		element.select('input[type="text"]').each(function(input, i){
			input.value = input.value.replace(/uid\=\&/, 'uid='+userId+'&');
		}.bind(this));
	}.bind(this));
    $$('.mymod').each(function(element, index) {
        element.style.color = '#ffffff';
    });
}

var video_requests_cname = "videoRequests";
function increment_video_views() {
	var value = get_video_views()+1;
	document.cookie = video_requests_cname+"=" +escape(value)+";path=/";
}

var mute_cta_name = "muteCTA";
function do_mute_cta() {    
	return true; // turning this functionality off for now
	var v = getCookie(mute_cta_name);
	if(v == null || v == "null") {
		v = Math.random() < .5;
		setCookie(mute_cta_name, v);
	}
	return v;
}

function get_video_views() {
    var v = getCookie(video_requests_cname);
    return v == null ? 0 : parseInt(v);
}

var video_preroll_interval = 4;
var video_preroll_remainder = 1;   // Checked before video starts playing so views will start at 0

function do_video_preroll() {

	var v = get_video_views();
	return (v % video_preroll_interval) == video_preroll_remainder;
}

function play_video(videoId) {
	thisMovie("video_player").play_video(videoId);
}

var highlighted_video;
function get_highlighted_video() {
    return highlighted_video;
}
function highlight_video(videoId) {
    highlighted_video = videoId;
	thisMovie("relatedCarousel").highlight_video(videoId);
}

function thisMovie(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {      
		return window[movieName];
	} else {
		return document[movieName];
	}
}

function set_preroll_remainder(n) {
    video_preroll_remainder = n;
}

var video_overlay_interval = video_preroll_interval;
var video_overlay_remainder = video_preroll_remainder;      // Checked after video starts playing so views will start at 1

function do_video_overlay() {
	var v = get_video_views();
	return (v % 4) == 1;    
}


/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year

var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
  for (var i = 0; i < s.length; i++){   
      // Check that current character is number.
      var c = s.charAt(i);
      if (((c < "0") || (c > "9"))) return false;
  }
  return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31;
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this;
}

function isDate(dtStr, message){
	var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strMonth=dtStr.substring(0,pos1);
	var strDay=dtStr.substring(pos1+1,pos2);
	var strYear=dtStr.substring(pos2+1);
	strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1);
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1);
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
	}
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	if (pos1==-1 || pos2==-1){
		alert(message || "The date format should be : mm/dd/yyyy");
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert(message || "Please enter a valid month");
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert(message || "Please enter a valid day");
		return false;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert(message || "Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert(message || "Please enter a valid date");
		return false;
	}
return true;
}

function validateDateField(dateValue, message){
	if (isDate(dateValue, message)==false){
		return false;
	}
	return true;
}


/* focus on newsletter signup if we click on subscribe link in header */
function focusNewsletterSignup() {
	$('subscribe').writeAttribute('href', 'javascript:void(0);');
	$('newsletter_signup').scrollTo();
	$('signup_text').focus();
	return false;
	
}
// attach to subscribe link un-ob
document.observe('dom:loaded', function() {
	if ($('subscribe') != undefined) {
		$('subscribe').observe('click', focusNewsletterSignup); 		
	}

});

/** DHTML email validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)  */
function validateEmailString(str) {

		var at="@";
		var dot=".";
		var lat=str.indexOf(at);
		var lstr=str.length;
		var ldot=str.indexOf(dot);
		
		if (str.indexOf(at)==-1){
		  return false;
		}
		if (str.indexOf(at)==0 || str.indexOf(at)==lstr){
		  return false;
		}
		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		   return false;
		}
		if (str.indexOf(at,(lat+1))!=-1){
		   return false;
		}
		if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		   return false;
		}
		if (str.indexOf(dot,(lat+2))==-1){
		   return false;
		}
		if (str.indexOf(" ")!=-1){
		   return false;
		}
 		return true;
}

/* tabs for popular_unit */
/**
 * @author Ryan Johnson <http://syntacticx.com/>
 * @copyright 2008 PersonalGrid Corporation <http://personalgrid.com/>
 * @package LivePipe UI
 * @license MIT
 * @url http://livepipe.net/control/tabs
 * @require prototype.js, livepipe.js
 */

if (typeof(Prototype) != "undefined" && typeof(Object.Event) != "undefined") {

    Control.Tabs = Class.create({
        initialize: function(tab_list_container,options){
            if(!$(tab_list_container))
                throw "Control.Tabs could not find the element: " + tab_list_container;
            this.activeContainer = false;
            this.activeLink = false;
            this.containers = $H({});
            this.links = [];
            Control.Tabs.instances.push(this);
            this.options = {
                beforeChange: Prototype.emptyFunction,
                afterChange: Prototype.emptyFunction,
                hover: false,
                linkSelector: 'li a',
                setClassOnContainer: false,
                activeClassName: 'active',
                defaultTab: 'first',
                autoLinkExternal: true,
                targetRegExp: /#(.+)$/,
                showFunction: Element.show,
                hideFunction: Element.hide
            };
            Object.extend(this.options,options || {});
            (typeof(this.options.linkSelector == 'string')
                ? $(tab_list_container).select(this.options.linkSelector)
                : this.options.linkSelector($(tab_list_container))
            ).findAll(function(link){
                return (/^#/).exec((Prototype.Browser.WebKit ? decodeURIComponent(link.href) : link.href).replace(window.location.href.split('#')[0],''));
            }).each(function(link){
                this.addTab(link);
            }.bind(this));
            this.containers.values().each(Element.hide);
            if(this.options.defaultTab == 'first')
                this.setActiveTab(this.links.first());
            else if(this.options.defaultTab == 'last')
                this.setActiveTab(this.links.last());
            else
                this.setActiveTab(this.options.defaultTab);
            var targets = this.options.targetRegExp.exec(window.location);
            if(targets && targets[1]){
                targets[1].split(',').each(function(target){
                    this.setActiveTab(this.links.find(function(link){
                        return link.key == target;
                    }));
                }.bind(this));
            }
            if(this.options.autoLinkExternal){
                $A(document.getElementsByTagName('a')).each(function(a){
                    if(!this.links.include(a)){
                        var clean_href = a.href.replace(window.location.href.split('#')[0],'');
                        if(clean_href.substring(0,1) == '#'){
                            if(this.containers.keys().include(clean_href.substring(1))){
                                $(a).observe('click',function(event,clean_href){
                                    this.setActiveTab(clean_href.substring(1));
                                }.bindAsEventListener(this,clean_href));
                            }
                        }
                    }
                }.bind(this));
            }
        },
        addTab: function(link){
            this.links.push(link);
            link.key = link.getAttribute('href').replace(window.location.href.split('#')[0],'').split('/').last().replace(/#/,'');
            var container = $(link.key);
            if(!container)
                throw "Control.Tabs: #" + link.key + " was not found on the page."
            this.containers.set(link.key,container);
            link[this.options.hover ? 'onmouseover' : 'onclick'] = function(link){
                if(window.event)
                    Event.stop(window.event);
                this.setActiveTab(link);
                return false;
            }.bind(this,link);
        },
        setActiveTab: function(link){
            if(!link && typeof(link) == 'undefined')
                return;
            if(typeof(link) == 'string'){
                this.setActiveTab(this.links.find(function(_link){
                    return _link.key == link;
                }));
            }else if(typeof(link) == 'number'){
                this.setActiveTab(this.links[link]);
            }else{
                if(this.notify('beforeChange',this.activeContainer,this.containers.get(link.key)) === false)
                    return;
                if(this.activeContainer)
                    this.options.hideFunction(this.activeContainer);
                this.links.each(function(item){
                    (this.options.setClassOnContainer ? $(item.parentNode) : item).removeClassName(this.options.activeClassName);
                }.bind(this));
                (this.options.setClassOnContainer ? $(link.parentNode) : link).addClassName(this.options.activeClassName);
                this.activeContainer = this.containers.get(link.key);
                this.activeLink = link;
                this.options.showFunction(this.containers.get(link.key));
                this.notify('afterChange',this.containers.get(link.key));
            }
        },
        next: function(){
            this.links.each(function(link,i){
                if(this.activeLink == link && this.links[i + 1]){
                    this.setActiveTab(this.links[i + 1]);
                    throw $break;
                }
            }.bind(this));
        },
        previous: function(){
            this.links.each(function(link,i){
                if(this.activeLink == link && this.links[i - 1]){
                    this.setActiveTab(this.links[i - 1]);
                    throw $break;
                }
            }.bind(this));
        },
        first: function(){
            this.setActiveTab(this.links.first());
        },
        last: function(){
            this.setActiveTab(this.links.last());
        }
    });
    Object.extend(Control.Tabs,{
        instances: [],
        findByTabId: function(id){
            return Control.Tabs.instances.find(function(tab){
                return tab.links.find(function(link){
                    return link.key == id;
                });
            });
        }
    });
    Object.Event.extend(Control.Tabs);

}



// for video page embed button blind effect, for ex.
var Toggler = Class.create({
	initialize: function(trigger_id, target_id, effect_str, effect_options_object) {
		this.execute = function(e) {
			Effect.toggle(this.target, this.effect, this.options);
			Event.stop(e);
		}
		this.trigger = $(trigger_id);
		this.target = $(target_id);
		this.effect = effect_str;
		this.options = effect_options_object;
		this.trigger.observe('click', this.execute.bindAsEventListener(this));
	}
});

// detect screen height, and return 16:9 dimensions for video player
function vidPlayerDimensionsByScreenHeight() {
	if(screen.height) {
		var screenHeight = screen.height;
		if(screenHeight <= 768) {
			return { x:544, y:306 };
		} else if(screenHeight <= 800) {
			return { x:608, y:342 };
		} else if(screenHeight <= 900) {
			return { x:784, y:441 };
		} else if(screenHeight <= 1000) {
			return { x:853, y:480 };
		} else {
			return { x:853, y:480 };
		}
	} else {
		return { x:853, y:480 };
	}
}

// match the width of the flashcontainer, so that the vid is centered regardless
function setVidPlayerContainerWidth(w) {
	var container = $$('.flashcontainer')[0];
	container.setStyle({width: w + "px"}); 
}

// for dynamic title/summary called from flash
function broadcastCurrentVideoInfo(title, summary, categories, models) {
    console.debug("broadcastCurrentVideoInfo", title, summary, categories, models);
    var dynamic_title = $('dynamic_video_title');
    var dyanmic_summary = $('dynamic_video_summary');
    var dynamic_categories = $('dynamic_post_categories');
    var dynamic_models = $('dynamic_post_models');

    dynamic_title.update(title);
    dyanmic_summary.update(summary);
    //
    generateAssociatedLinks("Posted in: ", dynamic_categories, categories, "title");
    generateAssociatedLinks("In this video: ", dynamic_models, models, "name");
}

function generateAssociatedLinks(label, div, objects, objLabel)
{
    if(objects && objects.length > 0)
    {
        var s = label;
        for(var i=0; i<objects.length; i++)
        {
            s += "<a href='" +objects[i].url + "'>" + objects[i][objLabel] + "</a>";
            if(i < objects.length-1)
            {
                s += ", ";
            }
        }
        div.update(s);
    }
    else
    {
        //div.hide();
    }

}

/* check for preview */
function checkForPreview() {
    if (getCookie('admin_preview') == 'enabled' && getCookie('admin_preview_date_pretty') != undefined) {
        preview_date = unescape(getCookie('admin_preview_date_pretty'));
        var elem = $('footer');
        if(elem) {
            elem.innerHTML += '<div class=\"preview clr\" style=\"color: #f0f;padding-top: 4px\">Preview mode: ' + preview_date + '</div>';
        }
    }
}


/* poll support */
// constructs the poll results markup given the json object
function pollResultsMarkup(r) {
    var questions = '';
    var num_questions = r.questions.size();
    for(i=0;i<num_questions;i++) {
        response_group = "<div class=\"response_group\">";
        questions += (response_group + "<div class=\"question\">" + r.questions[i].text + "</div>");
        var answers = '';
        var total_votes = r.questions[i].total_votes;
        var answer_array = r.questions[i].answers;
        var num_answers = answer_array.size();
        for(j=0;j<num_answers;j++) {
            poll_graph = "<div class=\"bar_container\">" +
            "<div class=\"bar transpng\" style=\"width: " + answer_array[j].percentage  + "%;\"> </div>" +
            "</div>";
            answer_link = (answer_array[j].link_text != '') ? "<br /><a href=\"" + answer_array[j].link_url + "\">" + answer_array[j].link_text + "</a>":'';
            answers += (poll_graph + "<div class=\"answer\">" + answer_array[j].percentage + "% - " + answer_array[j].text + answer_link + "</div>");
        }
        questions += (answers + "</div>");
    }
    var output = questions;
    return output;
}

function pollFlash(id, css_id, update_str) {
    var poll_container = getPollContainer(id);
    var elem = poll_container.select(css_id)[0];
    elem.update('<p class="transpng">' +update_str+ '</p>');
    elem.show();
}
function hidePollFlashes(id) {
    var poll_container = getPollContainer(id);
    poll_container.select('.flash').each(function(el){
        el.hide();
    });
    // alert('did it hide?');
}

function pollIdFromJSON(json) {
    return json['poll'].id;
}

function getPollContainer(id) {
    return ($('poll_'+id+'_container'));
}

function getPollForm(id) {
    return ($('poll_'+id));
}

function showPollAjaxIndicator(id) {
    var poll_container = getPollContainer(id);
    poll_container.select('.ajax_indicator')[0].show();
}

// triggers the update of poll results
function updatePollResults(poll_elem, json_obj) {
    $(poll_elem).insert(pollResultsMarkup(json_obj), 'bottom');
    $(poll_elem).show();
}

function updatePoll(json_obj) {
    var poll_container = getPollContainer(pollIdFromJSON(json_obj));
    $(poll_container).select('.query')[0].hide();
    var results = $(poll_container).select('.results')[0];
    updatePollResults(results, json_obj);
    poll_container.select('.ajax_indicator')[0].hide();
}

function validatePoll(id) {
    var ok = true;
    var poll = $(id);
    // for each response group, do we have one and only one checked radio button
    var response_groups = poll.select('.response_group');
    for (i=0;i<response_groups.size();i++) {
        ok &= (response_groups[i].select('input:checked[type=radio]').size() == 1);
    }
    return ok;
}

function appendPollCookie(obj) {
    var id = pollIdFromJSON(obj);
    var cookieName = 'mod_poll';
    if (getCookie(cookieName)) { // check for cookie: append if exists
        setCookie(cookieName, (getCookie(cookieName)+'|'+id), 2419200);
    } else { // create mod_poll cookie
        setCookie(cookieName, id, 2419200);
    }
}

function preflightPollResults(id) {
    getPollContainer(id).select('.query')[0].hide();
    showPollAjaxIndicator(id);
}

function postVoteJSON(e) {
    e.stop(e);
    // ensure all questions answered
    var poll_id = (this.id).split('_')[1];
    hidePollFlashes(poll_id);
    if (validatePoll("poll_" + poll_id)) {
        // setup request and success
        // hide query show indicator
        preflightPollResults(poll_id);
        new Ajax.Request("/poll/vote_json/"+poll_id, {
            method: 'post',
            parameters: $H(this.serialize(true)),
            requestHeaders: {Accept: 'application/json'},
            onSuccess: function(transport){
                var json = transport.responseText.evalJSON(true);
                if (json['success'] == 'true') {
                    //alert('success');
                    updatePoll(json);
                    appendPollCookie(json);
                } else {
                    alert('Unable to retrieve poll results at this time');
                }

            },
            onFailure: function(){ 
                alert('Unable to retrieve poll results at this time');
            }
        });
    } else {
        // not all poll questions were answered
        pollFlash(poll_id, '.error', "Please answer all poll questions.");
    }
}

function pollCheck(id) {
    if (getCookie('mod_poll')) {
        var id_array = $A(getCookie('mod_poll').split('|'));
        return (id_array.member(id));
    } else {
        return false;
    }
}

function getPollResults(id) {
    // get poll id for url
    // setup request and success
    preflightPollResults(id);
    new Ajax.Request("/poll/results_json/"+id, {
        method: 'post',
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if (json['success'] == 'true') {
                //alert('success');
                updatePoll(json);
            } else {
                pollFlash(pollIdFromJSON(json), '.error', "Couldn't retrieve poll results.");
                getPollContainer(pollIdFromJSON(json)).select('.ajax_indicator')[0].hide();
            }

        },
        onFailure: function(){
            console.log('Unable to retrieve poll results');
        }
    });
}

function pollQueryOrResults(id) {
    if (pollCheck(id)) {
        // get results
        getPollResults(id);
    }
}


/* end poll support */


function parseMysqlDate(date_string) {
    obj = new Object;
    var parts = date_string.split(/[-]/);
    obj['year'] = parts[0];
    obj['month'] = parseInt(parts[1], 10);
    obj['day'] = parseInt(parts[2], 10);
    return obj;
}



/* new generic form support: modForm */

// modForm util functions: targeting a parent container id allows more than one form to share flashes/ajax indicators and so on...
// form container id + .error or .notice, and the text to display in <p class="transpng">
function modFormFlash(container_id, css_type, text) {
    var elem = $(container_id).select(css_type)[0];
    elem.update(text);
    elem.show();
}

function modFormPrepareFlash(msg) {
    output = '<p class="transpng">' + msg + '</p>';
    return output;
}

// hide *all* flashes within the form container
function modFormHideFlashes(container_id) {
    var container = $(container_id);
    container.select('.flash').each(function(el) { el.hide() });
}

// show the ajax indicator for a given form
function modFormShowAjax(container_id) {
    var container = $(container_id);
    container.select('.ajax_indicator')[0].show();
}

// hide the ajax indicator
function modFormHideAjax(container_id) {
    var container = $(container_id);
    container.select('.ajax_indicator')[0].hide();
}

// disable the submit button for a given form (typically on submit, to prevent multiple clicks)
function modFormDisableSubmit(submit_id) {
    $(submit_id).disable();
    $(submit_id).setOpacity(.5);
}

// enable the submit button
function modFormEnableSubmit(submit_id) {
    $(submit_id).enable();
    $(submit_id).setOpacity(1);
}

// check radio button if exists
function modFormCheckRadioButton(form_field) {
    if ($(form_field)) {
        $(form_field).checked = true;
    }
}

// given the string of the object, and the obj of its properties iterate over the ids and fill in the values, don't force by default
function modFormPopulate(obj_name, o, force) {
    for(key in o) {
        if ($(obj_name + '_' + key)) {
            elem = $(obj_name + '_' + key);
            if (force || (elem.value == '')) {
                elem.value = o[key];
            }
        }
    }
}

/* end modForm support */


function jsDateToMysql(date1) {
  return date1.getFullYear() + '-' +
    (date1.getMonth() < 9 ? '0' : '') + (date1.getMonth()+1) + '-' +
    (date1.getDate() < 10 ? '0' : '') + date1.getDate();
}

/* ticket support */

// ticker for fashion week
function tickerMarkup(o) {
    output = "<div class=\"ticker_promo\">\n<div class=\"title\"><a href=\""+ o.url +"\" target=\"_blank\">"+ o.title +"</a></div>\n";
    if (o.summary != '' && o.summary != undefined){
        output += "<div class=\"summary\"><a href=\""+ o.url +"\" target=\"_blank\" >"+ o.summary +"</a></div>\n";
    }
    output += "</div>\n";
    return output;
}

function initializeTicker(o) {
    //console.debug('initTicker json', o);
    container = $('zone_ticker');
    //zone = tickerMarkup(o['zone']);
    //container.insert(zone, 'top');
    promos = '';
    for(i=0; i<o['items'].length; i++) {
        promos += tickerMarkup(o['items'][i]);
    }
    container = $('zone_ticker');
    rotating = container.select('.rotating_promos')[0];
    rotating.insert(promos, 'bottom');
    rotating.childElements().each(function(el){el.hide()});
    new Effect.BlindDown(container, {duration: .6});
    zt = new ZoneTicker(4000);
}

// require type='zone' and id= id of fashion week zone (1) for content blocks, as well as id of category for recent blog posts example id (18)
function getTicker(category_id, number_blog_posts, zone_type, zone_id) {
    // $('recent_blog_unit_loader').show();
    new Ajax.Request("/zone/ticker_json/", {
        method: 'post',
        parameters: {category_id: category_id, number_blog_posts: number_blog_posts, zone_type: zone_type, zone_id: zone_id},
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if (json['success'] = 'true') {
                initializeTicker(json);
            } 
        },
        onFailure: function(){ 
        }
    });
}

var ZoneTicker = Class.create({
  initialize: function(delay) {
      this.container= $$('.rotating_promos')[0]; 
      this.delay= delay; 
      this.mouseoverBol = 0; 
      this.pointer=0;
      this.max = this.container.childElements().length -1;
      this.opacitysetting=0.2;
      this.container.observe('mouseover', this.mOver.bind(this));
      this.container.observe('mouseout', this.mOut.bind(this));
      this.container.childElements()[0].show();
      var me = this;
      if (this.container.childElements().size() > 1) {
          setTimeout(function() {me.rotateMsg()}, me.delay);
      }
  },
  rotateMsg: function() {
    //alert(message);
    var me = this;
    if (this.mouseoverBol == 1) {
        setTimeout(function() {me.rotateMsg()}, 100);
    } else {
        new Effect.Fade(this.container.childElements()[this.pointer], {duration: .2, queue: 'end'});
        this.incrementPointer();
        new Effect.Appear(this.container.childElements()[this.pointer], {duration: .2, queue: 'end'});
        setTimeout(function() {me.rotateMsg()}, this.delay);
    }
  },
  mOver: function() {
      this.mouseoverBol = 1;
  },
  mOut: function() {
      this.mouseoverBol = 0;
  },
  incrementPointer: function() {
      this.pointer = (this.pointer >= this.max) ? 0 : this.pointer+1;
  }
});


function quiz_popup(e) {
    e.stop(e);
    window.open('/style_profile/', "_blank","location=0,status=0,scrollbars=0,toolbar=0,menubar=0,width=920,height=555");
}

function quizPopupLink() {
    if ($$('.quiz_popup_link').size() > 0) {
        $$('.quiz_popup_link').each(function(el){
            el.observe('click', quiz_popup);
        });
    }
}

function recordView(item_type, item_id) {
	var cookieName = "recently_viewed";
	var viewedItem = item_type + "-" + item_id.toString();
	var itemLimit = 10;
	if(getCookie(cookieName)) {
		setCookie(cookieName, getCookie(cookieName).replace(viewedItem + "|", "") + viewedItem + "|", 100000000);
		if(getCookie(cookieName).split("|").length-1 > itemLimit) {
			var firstItem = getCookie(cookieName).substr( 0, getCookie(cookieName).indexOf("|") + 1 ); // remove 1st item cookie to enforce item limit
			setCookie(cookieName,  getCookie(cookieName).replace(firstItem, ""));
		}	
	} else {
		setCookie(cookieName, viewedItem + "|", 100000000);
	}
}

function latest_c_block_markup(obj) {
    summary = (obj['summary'] != '') ? "<div class=\"summary\">" + obj['summary']  + "</div>" : '';
    action_url1 = (obj['url_text1'] != '') ? "<div class=\"action url1\"><a href=\"" + obj['url'] + "\" target=\"" + obj['url_target1'] +"\">" + obj['url_text1'] + "</a></div>" : '';
    action_url2 = (obj['url_text2'] != '') ? "<div class=\"action url2\"><a href=\"" + obj['url2'] + " target=\"" + obj['url_target2'] +"\">" + obj['url_text2'] + "</a></div>" : '';
    
    var ret = "<h3><a href=\"" + obj['url'] + "\">" + obj['title'] + "</a></h3>" + 
            "<div class=\"img\">" +
                "<a href=\"" + obj['url'] + "\"><img src=\"" + obj['img'] + "\" alt=\"\" /></a>" +
            "</div>" +
        "<div class=\"body\">" +
                summary +
                action_url1 +
                action_url2 +
        "</div>" +
    "<div class=\"clr\"></div>"; 
    return ret;
}

function latest_c_block_json(ids) {
    new Ajax.Request("/tout/latest_c_block_json/", {

        method: 'post',
        parameters: { tout_ids: ids },
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if (json['success'] == 'true' && json['touts']) {
                for (i=0; i< json['touts'].length; i++) {
                    console.log(json['touts'][i]);
                    var tout = latest_c_block_markup(json['touts'][i]);
                    var id = json['touts'][i]['id']
                    console.log(tout);
                    $('tout-id_' + id).update(tout);
                }
            } else {
                console.log('latest_c_block_json failed.');
            }
        }
    });
}

function latest_c_block() {
    if ($$('.latest_c_block_json').size() > 0) {
        var ids = '';
        $$('.latest_c_block_json').each(function(el) {
            var match = el.readAttribute('id').split('_');
            if (match[1]) {
                if (ids != '') {
                    ids += ',';
                }
                ids += match[1];
            }
        });
        latest_c_block_json(ids);
    }
}


// favorite support 
function remove_favorite_json(type, id) {
    new Ajax.Request("/dashboard/remove_favorite_json/", {
        method: 'post',
        parameters: {type: type, id: id },
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if (json['success'] == 'true') {
                if (json['composite_id']) {
                    $(json['composite_id']).fade();
                } else {
                    // no id to remove
                }
            } else {
                alert('Unable to remove favorite. Please try again later.');
            }
        }
    });
}

function remove_favorite(type, id) {
    var answer = confirm("Are you sure you wish to remove this Favorite?");
    if (answer) {
        remove_favorite_json(type, id);
    }
    return false;
}

function add_favorite_json(el) {
    // console.log($(el).up().up().id);
    var fav_id_str = $(el).up().up().id; // if we change the markup...
    var fav_id_array = fav_id_str.split('_');
    var fav_obj = fav_id_array[1].split('-');
    new Ajax.Request("/dashboard/add_favorite_json/", {
        method: 'post',
        parameters: {type: fav_obj[0], id: fav_obj[1] },
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if (json['success'] == 'true') {
                var elem = $('favorite_' + json['composite_id']);
                //var elem = $$('.favorite_button_container')[0];
                if (json['already_favorited'] == 'true') {
                    // show favorited
                    alert('You have already favorited this.');
                    elem.select('#favorite_this')[0].hide();
                    elem.select('#favorited')[0].show();
                } else {
                    // show favorite_this
                    elem.select('#favorite_this')[0].hide();
                    elem.select('#favorited')[0].show();
                }
            } else {
                // display some sort of error 
            }
    
        }
    });
}

function favorite_status(type, id) {
    new Ajax.Request("/dashboard/favorite_status_json/", {
        method: 'post',
        parameters: {type: type, id: id },
        requestHeaders: {Accept: 'application/json'},
        onSuccess: function(transport){
            var json = transport.responseText.evalJSON(true);
            if (json['success'] == 'true') {
                var elem = $('favorite_' + json['composite_id']);
                if(json['favorited'] == 'true') {
                    elem.select('#favorited')[0].show();
                } else {
                    elem.select('#favorite_this')[0].show();
                }
            } else {
                // default button already in place
            }

        }
    });
}

function favorite_button_generator() {
    if ($$('.favorite_button_container').size() > 0) {
        if (isLoggedIn()) {
            $$('.favorite_button_container').each(function(el) {
                //console.log($(el).id);
                var fav_id = $(el).id;
                var fav_split_id = fav_id.split('_'); // remove 'favorite_'
                var fav_id_arr = fav_split_id[1].split('-'); // split type-id
                // ajax type, id; return favorited true/false
                favorite_status(fav_id_arr[0], fav_id_arr[1]);
            });
        } // personalization shows favorite this (.logged_out)
    }

}
// end favorite support

// a/b testing support
function ab_test_css() {
    if ($$('body').size() > 0) {
        $$('body')[0].addClassName('test_b');
    }
}

// Returns false for "old" behavior, true for "new" behavior
function do_ab_test(ab_test_name, demoOnly) {
    var v = getCookie(ab_test_name);
    var param = swfobject.getQueryParamValue(ab_test_name);
    if (demoOnly != undefined && demoOnly && !param) {
        return false;
    }
    if (param || v == null || v == "null") {
        if (param) {
            v = param;
        } else {
            v = Math.random() < .5;
        }
        setCookie(ab_test_name, v);
    }
    console.debug(ab_test_name, v);
    var ret = (v == true || v == 'true');
    var action = ab_test_name + "_" + String(ret);
    _gaq.push(['_trackEvent', "Test", action]);
    if (ret) {
        ab_test_css();
    }
    return ret;
}

// TODO - move to core.js
function loadScript(url, callback) {
    var script = document.createElement("script")
    script.type = "text/javascript";
    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }
    script.src = url;
    document.getElementsByTagName('body')[0].appendChild(script);
}
