$(document).ready(function() {
    do_lightbox();
    $('title').bind("keyup", function() {
        do_lightbox();
    })
});

function submitForm(choice, cname, form) {
	//alert(form + ", " + cname + ", " + choice);
	//alert(document[form][cname]);
    document[form][cname].value = choice;
    document[form].submit();
}

function do_lightbox() {
    //$(function() {
        $('a.lightbox').lightBox(); // Select all links with lightbox class
    //});
}

function refreshAds(list) {
    for (var i = 0; i<list.length; i++) {
        var d = list[i];
        var url = 'http://' + document.location.host + '/openx/' + d + '/';
        //if (!isIE())
        //    $("#ad_" + d).fadeTo('fast', 0.01);
        $("#ad_" + d).load( url, { 'ajax': 'true' }, function() {
            //if (!isIE())
            //    $(this).fadeTo('slow', 1.0);
        });
    }
}

function pop_up_url(url, feat) {
    popup = window.open(url, "popupwindow", feat);
    popup.focus()
}

function fbs_click() {
    u=location.href;
    if(location.hash.length > 1) // if there is a hash, that url is the url of the content to pass on
        u = 'http://' + document.location.host + location.hash.substr(1);
    t=document.title;
    window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
    return false;
}
function tweet_click() {
    u=location.href;
    if(location.hash.length > 1) // if there is a hash, that url is the url of the content to pass on
        u = 'http://' + document.location.host + location.hash.substr(1);
    t=document.title;
    window.open('http://twitter.com/home?status='+encodeURIComponent(t)+': '+encodeURIComponent(u));
    return false;
}

// will not work if user is on logout page, since the view will attempt to logout again
function refresh() {
    document.location.reload(true);
}

function FBonlogin() {
    refresh();
    /*
    Boxy.ask("Would you like to sign up for the Washington Square News E-Delivery, our daily newsletter with links to articles, slideshows and events?",
               ["Sure!", "No thanks"], function(val) {
        if (val == 'Sure!') {
            FB.Connect.showPermissionDialog('email', 'refresh();');
        }
    }, {title: "While you're here...", modal: false, fixed: false});
    */
}


function logout(e) {
    Boxy.ask("Are you sure you want to log out of nyunews.com?",
               ["Yes", "No"], function(val) {
        if (val == "Yes") {
            $.ajax({
                url: 'http://127.0.0.1:8000/accounts/logout/',
                type: "GET",
                complete: function(one, two) {
                    Boxy.alert("You are now logged out. Come back soon!", null,
                        {title: "Goodbye!", modal: false});
                    refresh();
                }
            });
        }
    }, {title: "Logout", modal: false, fixed: false});
}

function do_logout() {
    $.ajax({
        url: 'http://127.0.0.1:8000/accounts/logout/',
        type: "GET",
        complete: function(one, two) {
            refresh();
        }
    });
}
function isIE() {
    if (navigator.userAgent.indexOf('MSIE') != -1)
        return true;
    return false;
}

function initEvents() {
    $(document).ready(function(){
        $("#accordion").accordion();
    });
}

function initSidebar() {
    $(document).ready(function() {
        $("#textlinks").get(0).innerHTML = '<p><a href="http://www.credit.com" target="_blank">free credit report</a></p><p><a href="http://www.inkhead.com/personalized-pens+personalized-pencils/personalized-pens-_ca-152-1.html" target="_blank">discount personalized pens</a></p><p><a href="http://www.autotropolis.com/cars/used/search-page-basic.aspx" target="_blank">buy used cars</a></p>';
    });
}

// Especially of use with genericajax, when a loaded div contains a javascript
// file meant to be included before document.ready. This takes the js file,
// loads it into the head, and then executes the callback function that requries
// that js, AFTER it's done loading it.
function loadScript(sScriptSrc,callbackfunction)
{
	//gets document head element
	var oHead = document.getElementsByTagName('head')[0];
	if(oHead)
	{
		//creates a new script tag
		var oScript = document.createElement('script');

		//adds src and type attribute to script tag
		oScript.setAttribute('src',sScriptSrc);
		oScript.setAttribute('type','text/javascript');

		//calling a function after the js is loaded (IE)
		var loadFunction = function()
			{
				if (this.readyState == 'complete' || this.readyState == 'loaded')
				{
					callbackfunction();
				}
			};
		oScript.onreadystatechange = loadFunction;

		//calling a function after the js is loaded (Firefox)
		oScript.onload = callbackfunction;

		//append the script tag to document head element
		oHead.appendChild(oScript);
	}
}


(function($) {

	function runTicker(settings) {
		if(settings.firstRun == 1){
			currentLength = settings.currentLength;
			currentItem = settings.currentItem;
			settings.firstRun = 0;
		}
		if(currentItem == settings.newsItemCounter + 1){
			currentItem = 0;
		}

		if(currentLength == 0) {
			if(settings.newsLinks[currentItem].length > 0) {
				$(settings.newsList).empty().append('<li><a href="'+ settings.newsLinks[currentItem] +'"></a></li>');
			}
			else {
				$(settings.newsList).empty().append('<li></li>');
			}
		}

		if( currentLength % 2 == 0) {
				placeHolder = settings.placeHolder1;
		}
		else {
			placeHolder = settings.placeHolder2;
		}

		if( currentLength <= settings.newsItems[currentItem].length + 1) {
			var tickerText = settings.newsItems[currentItem].substring(0,currentLength);
			if(settings.newsLinks[currentItem].length > 0) {
				$(settings.newsList + ' li a').text(tickerText + placeHolder);
			}
			else {
				$(settings.newsList + ' li').text(tickerText + placeHolder);
			}
			currentLength ++;
			setTimeout(function(){runTicker(settings); settings = null;},settings.tickerRate);
		}
		else {
			if(settings.newsLinks[currentItem].length > 0) {
				$(settings.newsList + ' li a').text(settings.newsItems[currentItem]);
			}
			else {
				$(settings.newsList + ' li').text(settings.newsItems[currentItem]);
			}
			currentLength = 0;
			currentItem ++;
			setTimeout(function(){runTicker(settings); settings = null;},settings.loopDelay);
		}
	}

	$.fn.extend({
		newsTicker: function(settings) {
			settings = jQuery.extend({
		 	  	newsList: "#news",
		   		tickerRate: 80,
		    	startDelay: 100,
		    	loopDelay: 3000,
		    	placeHolder1: " |",
		    	placeHolder2: "_"
			}, settings);

			var newsItems = new Array();
			var newsLinks = new Array();
			var newsItemCounter = 0;

			$(settings.newsList + ' li').each(function(){
				if($(this).children('a').length) {
					newsItems[newsItemCounter] = $(this).children('a').text();
					newsLinks[newsItemCounter] = $(this).children('a').attr('href');
				}
				else {
					newsItems[newsItemCounter] = $(this).text();
					newsLinks[newsItemCounter] = '';
				}
				newsItemCounter ++;
			});

			settings = jQuery.extend(settings,{
				newsItems: newsItems,
				newsLinks: newsLinks,
				newsItemCounter: newsItemCounter - 1,
				currentItem: 0,
				currentLength: 0,
				firstRun:1
			});

			setTimeout(function(){runTicker(settings); settings = null;},settings.startDelay);
		}

	});


})(jQuery);
