/**
 *  Global Behaviors and Functions
 */



var tickerDataLoaded = false;
var inAnimation = false; 
var Slider = function(el,nextControl,prevControl) {
    this.element = $(el);
    this.items = $('li',el);
    this.currentItem = this.items[0];
    this.count = 0;
    this.interval = 500;
    this.currentItem.style.display = "block";
    this.nextControl = $(nextControl);
    this.prevControl = $(prevControl);
    /* Click Bindings */
    this.nextControl.bind('click',{
        slider: this
    },function(e){
        e.data.slider.shownext();
    });

    this.prevControl.bind('click',{
        slider: this
    },function(e){
        e.data.slider.showprev();
    });
	
    /*
	 * Show the next item in line.
	 */
    this.shownext = function(){
        if(!inAnimation && (this.nextControl.disabled !== true)){
            inAnimation = true;
            if(this.count !== this.items.length-1){
                this.slideToLeftAndHide(this.currentItem);
                this.currentItem = $(this.currentItem).next("li");
                this.count++;
            }
        }
        this.checkAndToggleButtons();
    };

    /*
	 * Show the previous item in line.
	 */
    this.showprev = function(){
        if(!inAnimation && (this.prevControl.disabled !== true)){
            inAnimation = true;
            if(this.count !== 0){
                this.slideToRightAndHide($(this.currentItem).prev("li"));
                this.currentItem = $(this.currentItem).prev("li");
                this.count--;
            }
        }
        this.checkAndToggleButtons();
    };

    /**
	* Slide current item out to the left. Replace with next (hidden) list item.
	*/
    this.slideToLeftAndHide = function(el){
        $($(el).next()).animate( {
            width:"show"
        }, this.interval);
        $(el).animate( {
            marginLeft: $(el).outerWidth() * -1
            }, this.interval,null, function(){
            inAnimation = false;
            } );
    };
    /**
	* Slide current item out to the right. Replace with previous (hidden) list item.
	*/
    this.slideToRightAndHide = function(el){
        $(el).animate({
            marginLeft:"0px"
        }, this.interval, null, function(){
            inAnimation = false;
            } );
        $($(el).next()).animate({
            width:"hide"
        }, this.interval);
    };
    /**
	* If there are no more list items next or previous, disable appropriate control button.
	*/
    this.checkAndToggleButtons = function(){
        if(this.count === 0){
            this.disableButton(this.prevControl);
        }else{
            this.enableButton(this.prevControl);
        }
        if(this.count >= this.items.length-1){
            this.disableButton(this.nextControl);
        }else{
            this.enableButton(this.nextControl);
    	}
    };

    /**
	* Disable specified button.
	*/
    this.disableButton = function(el){
        el.disabled = true;
        $(el).addClass("disabledControl");
    };
	
    /**
	* Enable specified button.
	*/
    this.enableButton = function(el){
        el.disabled = false;
        $(el).removeClass("disabledControl");
    };
    // Gotta be at the bottom.
    this.checkAndToggleButtons();
};
/** News Ticker Javascript **/

/** 
* The default direction of scroll.
* 1 = Right-to-Left
* -1 = Left-to-Right
*/
var normal = -1;

/**
* Gotta hold this temporarily for mouseovers.
*/
var bufferDScroll = normal;

/**
* The d in Scroll to use. 
*/
var dScroll = normal;

/**
* The UL that we're using to scroll.
*/
var tickerUL;

/**
* The initial left margin of the first LI in the UL
*/
var marginLeft;

var tickerData;

/**
* A function to get the data via AJAX from RSS feed.
* Places list items in the marquee UL.
*/

function getTickerData(){
    $.get("?tag=marquee&feed=rss", function(data){
        var channel = data.getElementsByTagName('channel');
        var titles = data.getElementsByTagName('title');
        var links = data.getElementsByTagName('link');
        for(var i = 1; i < titles.length; i++){
            var d = "<a href='"+links[i].childNodes[0].nodeValue+"'>"+titles[i].childNodes[0].nodeValue+"</a>";
            $("#myTicker").append(d);
        }
				
    });
		
}

function insertMarquee()
{
	
    try
    {
        var next = $("#next");
        var prev = $("#prev");
        next.mousedown(
            function () {
                $('#myTicker').attr('direction','left');
				$('#myTicker').attr('scrollamount','55');
            }
            ).mouseup(
            function () {
				$('#myTicker').attr('scrollamount','1');
            }
			);
			
        prev.mousedown(
            function () {
                $('#myTicker').attr('direction','right');
            	$('#myTicker').attr('scrollamount','55');
            }
            ).mouseup(
            function () {
				$('#myTicker').attr('scrollamount','1');
            }
			);


        var ticker_holder = $('#holder');

        $(ticker_holder).html('<marquee id="myTicker" scrollamount="1" behavior="scroll"> </marquee>');
		$('#myTicker').attr('direction','right');
		setTimeout(function(){$('#myTicker').attr('direction','left');},500);
		
        $('#holder').hover(
            function() {
                $('marquee', this).get(0).stop();
            },
            function() {
                $('marquee', this).get(0).start();
            }
        );
    }
    catch (o) {}
}

var post = null;
submitForm = function(form, check, callback) {
    var infoarray = form.elements;
    var infostring = "";
    var valid = true;
    if (check === true) { valid = validate(form); }
    if (valid === true) {
        for (var i = 0; i < infoarray.length; i++) {
            if (infoarray[i].nodeName.toLowerCase() === "input" && infoarray[i].type !== "checkbox" && infoarray[i].type !== "radio" || infoarray[i].nodeName.toLowerCase() === "input" && (infoarray[i].type === "checkbox" || infoarray[i].type === "radio") && infoarray[i].checked === true || infoarray[i].nodeName.toLowerCase() === "textarea") {
                infostring += escape(infoarray[i].name) + "=" + escape(infoarray[i].value) + "&";
            } else if (infoarray[i].nodeName.toLowerCase() === "select") {
                for (var j = 0; j < infoarray[i].length; j++) {
                    if (infoarray[i].options[j].selected === true) {
                        infostring += escape(infoarray[i].name) + "=" + escape(infoarray[i].options[j].value) + "&";
                    }
                }
            }
        }
        infostring = infostring.substring(0, infostring.length - 1); // Remove extra ampersand
        /**Submit the form using JQuery! **/
        post = jQuery.ajax({
            url: form.action,
            data: infostring,
            async: true,
            type: "POST"
        });
        post.onreadystatechange = callback;
    } else {
        showMsg('Please check all required fields.');
    }
};

_defaultFormResponseHandler = function() {
    switch (post.readyState) {
        case 1:
        case 2:
        case 3:
            showMsg("Processing...", 0);
            break;
        case 4:
            var xmlDoc = post.responseXML;
            showMsg(xmlDoc.getElementsByTagName("msg")[0].childNodes[0].nodeValue, 3000);
            if (xmlDoc.getElementsByTagName("status")[0].childNodes[0].nodeValue === "OK") {
                if (xmlDoc.getElementsByTagName("redirect")[0].childNodes[0].nodeValue !== "") {
                    window.location.href = xmlDoc.getElementsByTagName("redirect")[0].childNodes[0].nodeValue;
                }
            }
            break;
        default:
            break;
    }
};
/** 
* form validation.
* @author Joel Salisbury
*/
validate = function(f) {
    var elements = f.elements;
    var validElements = [];
    var valid = true;
    for (var i = 0; i < elements.length; i++) {

        if (elements[i].className.indexOf("required") !== -1 && elements[i].value === '' && elements[i].disabled !==true) {
            jQuery(elements[i]).addClass('frm_invalid');
            valid = false;
        }else{ 
        	if(elements[i].className.indexOf("frm_email") !== -1 && !checkemail(elements[i].value) && elements[i].disabled !==true){
	            jQuery(elements[i]).addClass('frm_invalid');
	            valid=false;
	        }else{ 
	        	jQuery(elements[i]).removeClass('frm_invalid'); 
	        }
        }
		
    }
    return valid;
};
clearform = function(f) {
    document.getElementById(f).reset();
};

/**
* following code stolen from Jeff Anderson<jeff@codetoad.com>
*
*/

checkemail = function(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)===-1 || 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;
};


showMsg = function(msg){
    alert(msg);
};


/**
 * Simple Redirect Function
 * @param object param {url, timeout}
 */
var redirect = function(params){
    if(params.url){
        params.timeout = params.timeout ? params.timeout : 10000;
        setTimeout(function(){
            window.location = params.url;
        }, params.timeout);
    }
};

/**
 * Retrieves a GET variable from the current URL
 * @param string name
 */
var getVar = function(name){
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if (pair[0] === name) {
            return unescape(pair[1]);
        }
    }
};

$(document).ready(function(){
	
	
	$("ul.sf-menu").superfish().find('ul').bgIframe({});
	
	var num = $("#newsbytopic li").size();
	var numPerCol = 13
	var numCols = Math.ceil(num / numPerCol);
	$("#newsbytopic li").addClass("addthis");
	var currentCol = 1;
	for(var i = 1; i<=numCols; i++){
		var el = "navcol"+currentCol.toString();
		$("#newsbytopic").append("<div style='float:left;width:160px;' id='"+el+"'></div>");
			for(var x = 0; x <= numPerCol; x++){
				$("#"+el).append($("#newsbytopic li.addthis:first"));
				$("#"+el+" li.addthis").removeClass("addthis");
			}
		currentCol++;
	}
		
    try
    {
        // Install the Feed Icon
        $("#nav_top a:contains('Subscribe')").prepend('<img src="'+template_url+'/images/feed-icon-14x14.png" />');
        // BG lines on the fourth row
        $('#row4 .line1, #row4 .line2').css('height',$('#row4').height());
        $("a[href*='mp3']").wrap('<div class="audio"></div>');
        $('ul.sf-menu').superfish();
    }catch(e1){}
	
	
    try
    {
        $(".submitStory h4").click(function () {
            $(this).next("div").slideToggle();
        });
		
    } catch(e2){}
	
    try
    {
        getTickerData();
        insertMarquee();
		
    }catch(e3){}
	
    try
    {
        var slide1 = new Slider('#row1 ul.slider',"#row1 input[name='next']","#row1 input[name='previous']");
        var slide2 = new Slider('#row2 ul.slider',"#row2 input[name='next']","#row2 input[name='previous']");
		
    }catch(e4){}
	
	
	
    try
    {
        $("#beatList tr").mouseover(function() {
            $(this).addClass("over");
        }).mouseout(function() {
            $(this).removeClass("over");
        });
    }catch(e5){}
});