/*
 * Utility Functions
 */

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    } else { 
        expires = "";
    }
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}



function modify_extras_buttons(buttons_div, active_class, extras_div){
	elements = $(buttons_div).getElementsByTagName('li')
	for(i=0; i<elements.length; i++){
		if(elements[i].className == active_class){
			if(elements[i].id == 'active_extra'){
				elements[i].id = '';
				$(extras_div).innerHTML = '';
			}else{
				elements[i].id = 'active_extra';
			}
		}else if(elements[i].className != 'story-rank'){
			elements[i].id = ''
		}
	}
}

function highlight_div(div_id){
	new Effect.Pulsate(div_id)
}

function sort_table(table_id, sort_column){
	table_to_sort = $(table_id);
	dumpdiv = $('javadump')
	rows_to_sort = table_to_sort.getElementsByTagName('tr');
	row_count = rows_to_sort.length
	parent_node = rows_to_sort[1].parentNode;
	for(j=0; j <= 2; j++){
		//dumpdiv.innerHTML += '***' + j
		last_value =  rows_to_sort.item(1).getElementsByTagName('td').item(sort_column).innerHTML;
		last_node = rows_to_sort.item(1);
		for(i=1; i <= row_count - 2; i++){
			
			current_value = rows_to_sort.item(i).getElementsByTagName('td').item(sort_column).innerHTML;
			if(current_value < last_value){
				
				temp_current_node = rows_to_sort.item(i);
				temp_last_node = last_node;
				
				parent_node.replaceChild(temp_last_node, rows_to_sort.item(i));
				parent_node.replaceChild(temp_current_node, rows_to_sort.item(i-1));
				
				current_value = last_value;
				
			}
			last_node = rows_to_sort.item(i);
			last_value = current_value;
		}
	}
}

/*
 * This will show, highlight, and then fade a message, ultimately removing it from the page
 */
function temporarily_show(element_id, message) {
    // Create new element for our object
    var parent_element = $(element_id);
    var my_element = document.createElement('span');
    
    if (parent_element != null) {
        // Add the message
        my_element.innerHTML = message;
        my_element.className = 'status_message';
    
        // Show it and then fade it
        parent_element.innerHTML = ''
        parent_element.appendChild(my_element);
        Element.show(my_element);
        new Effect.Highlight(my_element,{ queue: {position:'end', scope: 'temp_queue'} } );
        setTimeout(function() {
            ;
            new Effect.Fade(my_element, { queue: {position:'end', scope: 'temp_queue'} } );
        }, 2000);
    }
}


/* 
 * Toggles map locations
 * If a status is passed in (accepted values are 'on' and 'off), the map location is set to that status
 * If a status is not passed in, the location is toggled
 */
function toggle_location(location_id, status) {
    // Grab the DOM nodes
    var location_marker = $('map_marker_'+location_id);
    if (location_marker == null) return false;
    
    // Determine the status
    var is_marker_already_on = Element.hasClassName(location_marker, 'current-location');
    if ((status == null || status == '') || (status != 'on' && status != 'off')) {
        status = is_marker_already_on ? 'off' : 'on';
    }
    
    // Set current node
    var current_locations = document.getElementsByClassName('current-location');
    loop_end = current_locations.length;
    for (i=0; i<loop_end; i++){
        if (current_locations[i] != location_marker) {
            Element.removeClassName(current_locations[i], 'current-location');
        } else {
            if (status == 'off'){
                Element.removeClassName(location_marker, 'current-location');
            }
        }
    }
    if (status == 'on') {
        if (!is_marker_already_on) {
            Element.addClassName(location_marker, 'current-location');
        }
    }
    
    // Set the cookie to hide the map helper
    var hide_map_helper = readCookie("hide_map_helper");
    if (!(hide_map_helper == true || hide_map_helper == 'true')) {
        createCookie('hide_map_helper', true, 365);
    }
    
}


function hide_helper() {
    new Effect.Fade('map-helper', {duration:0.7});
}

function toggle_map_key() {
    var map_key = $('map_key');
    var map_key_close_link = $('a-map_key-close');
    if (map_key == null || map_key_close_link == null) return false;
    if (Element.hasClassName(map_key, 'map_key-opened')) {
        map_key.className = 'map_key-closed';
        Element.hide(map_key_close_link);
    } else {
        map_key.className = 'map_key-opened';
        Element.show(map_key_close_link);
    }
}


/*
Clear default form value script- by JavaScriptKit.com
Featured on JavaScript Kit (http://javascriptkit.com)
Visit javascriptkit.com for 400+ free scripts!
*/

function clearText(thefield){
  if (thefield.defaultValue==thefield.value)
  thefield.value = ""
} 




/*
 * This function is called before users upload pictures
 */
function image_upload_submit(form_id) {
    our_form = $(form_id)
    if (our_form == null) {
        return false;
    }
    
    if ($('agree_to_terms').checked != true) {
        alert('You must agree to the FanNation User Agreement!')
        return false;
    } else {
        our_form.submit();
        return true;
    }
}

blog_post_tag_warning = 0;
function blog_post_submit_form(form_id) {
    var tag_field = $('blog_post_tags');
    if (tag_field == null) {
        return false;
    } else {
        if (tag_field.value == '' && blog_post_tag_warning < 1) {
            alert("Please tag your blog post with key words to help other Fans find your post.");
            blog_post_tag_warning++;
        } else {
            var blog_form = $(form_id)
            if (blog_form == null) {
                return false;
            } else {
                tinyMCE.triggerSave(true,true);
                blog_form.onsubmit();
                $('blog_post_submit').disabled = true;
                return true;
            }
        }
    }
}



/*
 * Functions used to give Ajax feedback
 */

function display_ajax_spinner(container_id, message, options) {
    var container_node = $(container_id);
    if (container_node == null) {
        return false;
    } else {
        if (options == null) {
            options = {from:0.0, to:1.0, duration:0.5}
        }
        message = message == null ? 'Loading' : message;
        var temp_id = 'ajax_temp' + parseInt(Math.random() * 1000000, 10) + '_container'
        container_node.innerHTML = '<div id="' + temp_id + '" class="ajax-spinner" style="display:none;">' + message + '</div>';
        new Effect.Appear(temp_id, options)
        return temp_id;
    }
}

function hide_form(form_id) {
    var my_form = $(form_id);
    if (my_form == null) {
        return false;
    } else {
        Form.disable(my_form);
        Element.hide(my_form);
    }
}

function show_form(form_id) {
    var my_form = $(form_id);
    if (my_form == null) {
        return false;
    } else {
        Form.enable(my_form);
        Element.show(my_form);
    }
}


/* --- Front Page Callout Code --- */
// set variables for fading
var callout_counter = 0
var wait = 5500;

// the function that performs the fade
function swapFade() {
    Effect.Fade(callouts[callout_counter], { duration:1, from:1.0, to:0.0 });
    callout_counter++;
    if (callout_counter == callouts.length) {
        callout_counter = 0;
    }
    Effect.Appear(callouts[callout_counter], { delay: 0.5, duration:1, from:0.0, to:1.0 });
}

// function that starts fader on a timer
function startFader() {
    setInterval('swapFade()',wait);
}



/* --- Search autocomplete --- */
function tag_load() {
    new Ajax.Request('/fannation/tags_for_lookup',
            {
                asynchronous: true,
                onSuccess: function(t) {
                    eval(t.responseText);
                    new Autocompleter.Local('main_search',
                                            'tag_lookup_autocomplete',
                                            tags,
                                            {
                                                fullSearch: true,
                                                frequency: 0,
                                                minChars: 1
                                            });
                }
            }
        );
}


function tr_photo_pick(photo_id, filename) {
    var photo_container = $('tr_photo_picker');
    var ap_photos = photo_container.getElementsByTagName('img');
    var photo_field = $('truth_rumor_photo_source');
    var selected_photo = $('Image_'+photo_id);
    if (photo_container == null || ap_photos == null || photo_field == null) {
        return false
    } else {
        var number_of_photos = ap_photos.length
        for (var i=0; i<number_of_photos; i++) {
            if (ap_photos[i] != selected_photo) {
                ap_photos[i].className = '';
            } else {
                ap_photos[i].className = 'selected';
            }
        }
        photo_field.value = filename;
        var photo_credit_field = $('truth_rumor_photo_credit');
        if (photo_credit_field != null && photo_credit_field.value == '') {
            photo_credit_field.value = 'AP';
        }
        return true;
    }
};


function fpn_photo_pick(photo_id, filename) {
    var photo_container = $('fpn_photo_picker');
    var ap_photos = photo_container.getElementsByTagName('img');
    var photo_field = $('featured_player_news_photo_source');
    var selected_photo = $('Image_'+photo_id);
    if (photo_container == null || ap_photos == null || photo_field == null) {
        return false
    } else {
        var number_of_photos = ap_photos.length
        for (var i=0; i<number_of_photos; i++) {
            if (ap_photos[i] != selected_photo) {
                ap_photos[i].className = '';
            } else {
                ap_photos[i].className = 'selected';
            }
        }
        photo_field.value = filename;
        var photo_credit_field = $('featured_player_news_photo_credit');
        if (photo_credit_field != null && photo_credit_field.value == '') {
            photo_credit_field.value = 'AP';
        }
        return true;
    }
};

/* --- combo code for opening and closing the map --- */

Effect.OpenUp = function(element) {
    element = $(element);
    new Effect.BlindDown(element, arguments[1] || {});
}

Effect.CloseDown = function(element) {
    element = $(element);
    new Effect.BlindUp(element, arguments[1] || {});
}

Effect.Combo = function(element) {
    element = $(element);
    if(element.style.display == 'none') { 
         new Effect.OpenUp(element, arguments[1] || {}); 
    }else { 
         new Effect.CloseDown(element, arguments[1] || {}); 
    }
}

/* --- Checks to see if enter was pressed, if so it submits the form via the click function (so the onSubmit is run) --- */
function check_enter(event, submit_button){
		if(window.event) // IE
		{
			keynum = event.keyCode;
		}
		else if(event.which) // Netscape/Firefox/Opera
		{
			keynum = event.which;
		}
		if(keynum == 13){
			$(submit_button).click();
			return false;
		} else {
			return true;
		}
	}











/* --- LightBox Specific Stuff --- */
/* Borrowed heavily from ParticleTree: http://particletree.com/features/lightbox-gone-wild */
function open_lightbox() {
    if (display_lightbox()) {
        // Sometimes this fires after content is loaded?
        //lightbox_loading();
    }
};

function display_lightbox() {
    var lightbox = $('lightbox');
    var overlay = $('lightbox_overlay');
    if ((lightbox == null) || (overlay == null)) return false;
    if ((BrowserDetect.browser == 'Explorer') && (BrowserDetect.version < 7) && (BrowserDetect.OS == 'Windows')) {
        lb_hide_selects('hidden');
        lb_get_scroll();
        lb_prepare_ie('100%', 'hidden');
        lb_set_scroll(0,0);
    }
    overlay.style.display = 'block';
    lightbox.style.display = 'block';
    return true;
};


function lightbox_loading() {
    var lightbox = $('lightbox');
    if (lightbox == null) return false;
    lightbox.innerHTML = '<div id="lightbox_content"><p>Loading&hellip;</p><p><a href="#" onclick="close_lightbox();">Close Lightbox</a></p></div>';
    return true;
};

function close_lightbox() {
    var lightbox = $('lightbox');
    var overlay = $('lightbox_overlay');
    if ((lightbox == null) || (overlay == null)) return false;
    lightbox.innerHTML = ''
    if ((BrowserDetect.browser == 'Explorer') && (BrowserDetect.version < 7) && (BrowserDetect.OS == 'Windows')) {
        lb_hide_selects('visible');
        lb_set_scroll(0,this.yPos);
        lb_prepare_ie("auto", "auto");
    }
    lightbox.style.display = 'none';
    overlay.style.display = 'none';
    return true;
};





function lb_hide_selects(visibility){
    var selects = document.getElementsByTagName('select');
    var lightbox_selects = $('lightbox').getElementsByTagName('select');
    if ((selects != null) && (lightbox_selects != null)) {
        selects = selects - lightbox_selects
    }
    for(i = 0; i < selects.length; i++) {
        selects[i].style.visibility = visibility;
    }
};


// Ie requires height to 100% and overflow hidden or else you can scroll down past the lightbox
function lb_prepare_ie(height, overflow){
    bod = document.getElementsByTagName('body')[0];
    bod.style.height = height;
    bod.style.overflow = overflow;

    htm = document.getElementsByTagName('html')[0];
    htm.style.height = height;
    htm.style.overflow = overflow; 
}


// Taken from lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
function lb_get_scroll(){
    if (self.pageYOffset) {
        this.yPos = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop){
        this.yPos = document.documentElement.scrollTop; 
    } else if (document.body) {
        this.yPos = document.body.scrollTop;
    }
}
    
function lb_set_scroll(x, y){
    window.scrollTo(x, y); 
}


/* Browser detection from PPK */
/* http://www.quirksmode.org/js/detect.html */
var BrowserDetect = {
    init: function () {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
            || this.searchVersion(navigator.appVersion)
            || "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data) {
        for (var i=0;i<data.length;i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function (dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
    },
    dataBrowser: [
        {   string: navigator.userAgent,
            subString: "OmniWeb",
            versionSearch: "OmniWeb/",
            identity: "OmniWeb"
        },
        {
            string: navigator.vendor,
            subString: "Apple",
            identity: "Safari"
        },
        {
            prop: window.opera,
            identity: "Opera"
        },
        {
            string: navigator.vendor,
            subString: "iCab",
            identity: "iCab"
        },
        {
            string: navigator.vendor,
            subString: "KDE",
            identity: "Konqueror"
        },
        {
            string: navigator.userAgent,
            subString: "Firefox",
            identity: "Firefox"
        },
        {
            string: navigator.vendor,
            subString: "Camino",
            identity: "Camino"
        },
        {       // for newer Netscapes (6+)
            string: navigator.userAgent,
            subString: "Netscape",
            identity: "Netscape"
        },
        {
            string: navigator.userAgent,
            subString: "MSIE",
            identity: "Explorer",
            versionSearch: "MSIE"
        },
        {
            string: navigator.userAgent,
            subString: "Gecko",
            identity: "Mozilla",
            versionSearch: "rv"
        },
        {       // for older Netscapes (4-)
            string: navigator.userAgent,
            subString: "Mozilla",
            identity: "Netscape",
            versionSearch: "Mozilla"
        }
    ],
    dataOS : [
        {
            string: navigator.platform,
            subString: "Win",
            identity: "Windows"
        },
        {
            string: navigator.platform,
            subString: "Mac",
            identity: "Mac"
        },
        {
            string: navigator.platform,
            subString: "Linux",
            identity: "Linux"
        }
    ]

};
BrowserDetect.init();

/* initialize app */

fannation = {};
fannation.apps = fannation.apps || {};

fannation.apps.Quote = Class.create();
fannation.apps.Quote.prototype = {
	
	initialize: function(id,type) {
		this.clearQuote();
		this.quotable_id = id;
		this.quotable_type = type || 'Comment';
		this.setQuotableId(this.quotable_id);
		this.setQuotableType(this.quotable_type);
		this.displayQuotedText(this.quotable_id);
	},
	setQuotableId: function(id) {
		$('comment_quotable_id').value = id;
	},
	setQuotableType: function(type) {
		$('comment_quotable_type').value = type;
	},
	displayQuotedText: function(id) {
		var quoted_text = $('comment_body_' + id).innerHTML.stripTags().strip();
		var selected_text = (!!document.getSelection) ? document.getSelection()+'' : (!!window.getSelection) ? window.getSelection()+'' : document.selection.createRange().text+'';	
		if (selected_text.length > 0 && quoted_text.indexOf(selected_text) > -1) {
			quoted_text = selected_text.strip();
		}
		/* show */
		$('comment_quoted_text').value = quoted_text;
		$('quoted-comment').show();
		new Effect.ScrollTo('add_comment_div');
	},
	clearQuote: function() {
		$('quoted-comment').hide();
		$('comment_quotable_id').value = '';
		$('comment_quotable_type').value = '';
		$('comment_quoted_text').value ='';
	}
}

function setQuotable(id) {
	var quotable = new fannation.apps.Quote(id,type);
}

function swap_headshot(type, number, id, sport_id) {
    if (id == null || number == null || type == null) { return false;}
	sport_root = {}
	sport_root["1"] = 'football/nfl'
	sport_root["2"] = 'baseball/mlb'
	sport_root["3"] = 'basketball/nba'
    $('player_picker_headshot_'+type+'_'+number).innerHTML = '<img src="http://i.a.cnn.net/si/images/' + sport_root[sport_id + ''] + '/players/'+id+'_small.jpg" />'
}


// Suckerfish menu
Event.observe(window, 'load', function() {
   $$('.sub-menus li').each(function(node) {
     Event.observe(node, 'mouseenter', function(event) { node.addClassName('hover') });
     Event.observe(node, 'mouseleave', function(event) { node.removeClassName('hover') });
   });
});