function hoverLinks(el) {
	
	/***
     * Controls the behavior of the right-hand "callout" lis.
     * Can be moved to external script, etc.
     */
    //(function(){
        //var el = document.getElementById('hoverLinks');
        var lis = YAHOO.util.Dom.getChildren(el);
        var bars = YAHOO.util.Dom.getElementsByClassName('bar_container');

        YAHOO.util.Event.addListener(lis,'mouseover',function(e){
            for(var i = 0; i < lis.length; i++){
                YAHOO.util.Dom.removeClass(lis[i],'hover_link');
            }
            YAHOO.util.Dom.addClass(this,'hover_link');
        });

        YAHOO.util.Event.addListener(lis,'mouseout',function(e){
            YAHOO.util.Dom.removeClass(this,'hover_link');
        });

        YAHOO.util.Event.addListener(lis,'click',function(e){
            var elId = this.id.substr(3);

            for(var i = 0; i < lis.length; i++){
                YAHOO.util.Dom.removeClass(lis[i],'clicked');
            }
            YAHOO.util.Dom.addClass(this,'clicked');

            for(var i = 0; i < bars.length; i++){
                YAHOO.util.Dom.addClass(bars[i],'noD');
            }
            YAHOO.util.Dom.removeClass('bars_' + elId,'noD');
        });
    //}());
	
}

function addTextSizes(elements) {
	
	for(var i = 0; i < elements.length; i++){
		
	    var el = elements[i];
		addTextSize(el)

	}
	
}

function addTextSize(el) {
	var sTag = el.getElementsByTagName('span')[0];
    var sz = parseInt(el.style.width,10);

    if(sz >= 84) YAHOO.util.Dom.addClass(sTag,'big');
    else if(sz < 84 && sz >= 16) YAHOO.util.Dom.addClass(sTag,'med');
    else if(sz < 16) YAHOO.util.Dom.addClass(sTag,'sm');
}

function checkForm(frm) {
	var buckets_valid = formBucketSubmit(frm);
	var industries_valid = checkIndustriesSubmit(frm);
	if (!buckets_valid || !industries_valid){ 
		return false;
	}
	else {
		return true;
	}
}

// FIXME only check first page
function checkIndustriesSubmit(frm) {
	
	var display_error = false;
	var has_industries = document.getElementById('has_industries')

	if (has_industries) {
		if (!has_industries.value) {
			errorMsg( "Please add at least one industry", 'industries_error')
			display_error = true;			
		}
	}

	if (display_error){ 
		return false;
	}
	else {
		return true;
	}
	
}

function createIndustryHeader(quiz_id, name, id, user_id, data_type) {
	if (data_type == 'industry') {
		return "<h2 class=\"left\"><img id=\"img_back\" src=\"" + MEDIA_URL + "/media/images/icons/icon_carat_back.gif\" class=\"arrow\"  onclick=\"prevNext("+quiz_id+","+id+","+user_id+",'prev');\"> "+name+" <img id=\"img_forward\" src=\"" + MEDIA_URL + "/media/images/icons/icon_carat_fwd.gif\" class=\"arrow\" onclick=\"prevNext("+quiz_id+","+id+","+user_id+",'next');\"></h2>";		
	}
	else {
		return "<h2 class=\"left\">Compare with Yourself</h2>";
	}
}

function createIndustryDiv(name, avg, desc, color, id, data_type) {
	ind_div = "<div class=\"bar\"><div id=\""+data_type+id+"\" class=\"grad_bar "+color+" grow\" style=\"width:"+ avg +"%\" ><span>"+ name +"</span><div class=\"ttData noD\"><strong>"+ avg +" percentile</strong><br>"+ desc +"</div></div></div>";
	
	return ind_div
}

function prevNext(quiz_id, current_industry_id, user_id, prev_or_next) {
	var position = window.industry_ids.indexOf(current_industry_id)
	if (prev_or_next == 'prev') {
		// prev
		position -= 1
	}
	else {
		// next
		position += 1
	}
	
	// at beginnning
	if (position == -1) {
		position = window.industry_ids.length-2
		// final element is null
	}
	// reached end
	if (position >= window.industry_ids.length-1) {
		position = 0
	}
	doQuizCompare(quiz_id, window.industry_ids[position], user_id)
}

function doShare(quiz_id) {
	
	var url = "/quizzes/share/send/"+quiz_id+"/"
	var callback = {
		success: function(o) {
			addShareData(o.responseText);
		},
		failure: function(o) {
			document.getElementById('compare').innerHTML = ("An error has occurred. Please try again later"); 
		}
	}
	var transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
	
}

function doFriendCompare(quiz_id, user_id, me_id) {
	
	var url = "/quizzes/friends/"+quiz_id+"/"+user_id+"/"
	var callback = {
		success: function(o) {
			loopCompareData(quiz_id, me_id, o.responseText, 'friend');
			addGrade(o.responseText, 'friend')
			//addIndustryWidget(o.responseText);
			//addFriendCompareData(o.responseText)
			unset_loading_image('friend_loading');
		},
		failure: function(o) {
			document.getElementById('compare_friends').innerHTML = ("An error has occurred. Please try again later"); 
		}
	}
	set_loading_image('large', 'friend_loading');
	var transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
	
}

function doQuizCompare(quiz_id, id, user_id) {
	
	var url = "/quizzes/compare/"+quiz_id+"/"+id+"/"+user_id+"/"
	var callback = {
		success: function(o) {
			loopCompareData(quiz_id, user_id, o.responseText);
			//addIndustryWidget(o.responseText);
			unset_loading_image();
		},
		failure: function(o) {
			document.getElementById('compare').innerHTML = ("An error has occurred. Please try again later"); 
		}
	}
	set_loading_image('large');
	var transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
	
}

function addSubIndustries() {
	
	var url = "/quizzes/addindy/"
	var callback = {
		success: function(o) {
			addIndustriesToPage(o.responseText);
			document.getElementById('has_industries').value=1
			
		},
		failure: function(o) {
			document.getElementById('added_industries').innerHTML = ("Please select at least one industry."+o.responseText); 
		}
	}
	this.form = document.getElementById('quiz');
	YAHOO.util.Connect.setForm(this.form);
	this.cache = YAHOO.util.Connect._sFormData;

	var transaction = YAHOO.util.Connect.asyncRequest('POST', url, callback, this.cache);
	
}

function removeSubIndustries() {
	
	var url = "/quizzes/removeindy/"
	var callback = {
		success: function(o) {
			removeIndustriesFromPage(o.responseText);
		},
		failure: function(o) {
			document.getElementById('added_industries').innerHTML = ("Please select at least one industry."+o.responseText); 
		}
	}
	this.form = document.getElementById('quiz');
	YAHOO.util.Connect.setForm(this.form);
	this.cache = YAHOO.util.Connect._sFormData;
	var transaction = YAHOO.util.Connect.asyncRequest('POST', url, callback, this.cache);
	
}

function addIndustriesToPage(response) {
	
	results = _getData(response)
	
	for (this_res = 0; this_res < results.length; this_res ++) {
		if (optionDoesNotExist(results[this_res].subindustry)) {
			addOption(results[this_res].subindustry, results[this_res].id);
		}
	}
	
}

function removeIndustriesFromPage(response) {
	
	results = _getData(response)
	
	for (this_res = 0; this_res < results.length; this_res ++) {
		removeOption(results[this_res].subindustry, results[this_res].id);
	}
	
}

function optionDoesNotExist(curText) {
	theSel = document.forms['quiz'].added
	
	if (theSel.options.length <=0 ) {
		return true		
	}

	for (this_sel = 0; this_sel <= theSel.options.length; this_sel++) {
		
		if (theSel[this_sel]) {
			
			selHtml = theSel[this_sel].innerHTML
			if (curText.match(selHtml)){
				return false
			}
			
		}
		
	}
	
	return true
}

function addOption(text, value) {
	
	theSel = document.forms['quiz'].added
	var newOpt = new Option(text, value);
    var selLength = theSel.length;
	theSel.options[selLength] = newOpt;
	
}

function removeOption(text, value) {
	
	theSel = document.forms['quiz'].added
	var selIndex = theSel.selectedIndex;
	  if (selIndex != -1) {
	    for(i=theSel.length-1; i>=0; i--)
	    {
	      if(theSel.options[i].selected)
	      {
	        theSel.options[i] = null;
	      }
	    }
	    if (theSel.length > 0) {
	      theSel.selectedIndex = selIndex == 0 ? 0 : selIndex - 1;
	    }
	  }
	
}

function _getData(response) {
	var data = ""
	try {
	    data = YAHOO.lang.JSON.parse(response);
	}
	catch (e) {
	    document.getElementById('compare').innerHTML = ("A parsing error has occurred. Please try again later"); 
	}
	return data;
}

function addShareData(response) {

	data = _getData(response)
	form = data[0]
	if (document.getElementById('share_results')) {
		document.getElementById('share_results').innerHTML = "<table><div>"+form+"</div></table>"
	}
	
}

function addFriendCompareData(response) {
	
	data = _getData(response)
	results = data[0]
	
	if (results) {
		document.getElementById('compare_friends').innerHTML = "<h5>Compared to you:</h5><br/>"+results				
	}
	else {
		document.getElementById('compare_friends').innerHTML = "You haven't taken this quiz yet!"
	}
}

function addIndustryWidget(response) {
	
	data = _getData(response)
	results = data[1]
	document.getElementById('industry_widget').innerHTML = results[0]['industry_preview']
	
}

function addGrade(response, data_type) {

	if (!data_type) {
		data_type = "industry"
	}
	
	data = _getData(response)
	results = data[0]
	if (!results) {
		return false;
	}
	grade_div = YAHOO.util.Dom.get('friend_grade')
	grade_div.innerHTML = "<h2>"+results[0].grade+"</h2>"
	
}

function loopCompareData(quiz_id, user_id, response, data_type) {
	
	if (!data_type) {
		data_type = "industry"
	}
	
	var final_traits = Array(window.trait_sort_order.length);
	var this_trait = 0;
	
	var results = ""
	data = _getData(response)
	results = data[0]
	if (!results) {
		return false;
	}
	for (this_res = 0; this_res < results.length; this_res ++) {
		if (this_res == 0) {
			appendHeader(quiz_id, results[this_res].industry_name, results[this_res].industry_id, user_id, data_type);
		}
		trait_index = getTraitIndex(results[this_res].trait_id) 
		final_traits[trait_index] = createIndustryDiv(results[this_res].trait_display_name, results[this_res].avg, results[this_res].desc, results[this_res].color, results[this_res].trait_id, data_type)
	}
	
	appendTraits(final_traits, data_type)
	
	for (this_res = 0; this_res < results.length; this_res ++) {
		el = document.getElementById(data_type+results[this_res].trait_id)
		addTextSize(el)
	}
	
}

function getTraitIndex(trait_id) {
	var tInt = parseInt(trait_id)
	return window.trait_sort_order.indexOf(tInt)
}

function appendHeader(quiz_id, name, id, user_id, data_type) {
	var header = ""
	if (data_type == 'industry') {
		header = YAHOO.util.Dom.get('compare_header')
	} else {
		header = YAHOO.util.Dom.get('compare_friend_header')
	}
	header.innerHTML = createIndustryHeader(quiz_id, name, id, user_id, data_type)
}

function appendTraits(final_traits, data_type) {
	//$("#compare").fadeOut("slow");
	var compare = ""
	
	if (data_type == 'industry') {
		compare = YAHOO.util.Dom.get('compare')		
	}
	else {
		compare = YAHOO.util.Dom.get('compare_friends')	
	}
	
	var html = ""
	compare.innerHTML = ""
	for (this_final_trait = 0; this_final_trait < window.trait_sort_order.length; this_final_trait +=1) {
		html += (final_traits[this_final_trait]);
	}
	compare.innerHTML = html;
	//alert(html)
	//$("#compare").fadeIn("slow");
}

// fix for indexOf in ie
if(!Array.indexOf){
	    Array.prototype.indexOf = function(obj){
	        for(var i=0; i<this.length; i++){
	            if(this[i]==obj){
	                return i;
	            }
	        }
	        return -1;
	    }
}

function setSlidersFromParams(post_items) {
	var sliders = PB.getSliders()
	for (var this_item = 0; this_item <= sliders.length; this_item ++) {
		this_slider = PB.getSlider(this_item)
		
		if (this_slider) {
			if (post_items[this_slider.id]){
				this_slider.setValue(post_items[this_slider.id],true);	
				listenerUpdate(this_slider, post_items[this_slider.id])	
			}
			else {
				this_slider.setValue(0,true);	
				listenerUpdate(this_slider, 0)
			}
		}
		
	}
}

function copyTraitsToTextarea() {
	document.path_101_traits_form.path_101_traits_embed.value = "<!-- BEGIN PATH101 CODE --><div class='path_101' style='width:270px; border: 1px solid #999; padding: 10px;'>" + YAHOO.util.Dom.get('path_101_traits').innerHTML + "</div><!-- END PATH101 CODE -->"
}

