// Define cookie get/set functions
var createCookie = function(name,value,days) {
    if ( days ) {
        var date = new Date();

        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    } else {
        var expires = "";
    }
    document.cookie = name+"="+value+expires+"; path=/";
};

var readCookie = function(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;
};

var eraseCookie = function(name) {
    createCookie(name,"",-1);
};

// Define a function that - when called - will invoke the subscription-protected page that checks $cms.subscriptionUser and sets js var AND cookies accordingly.
var setLoginCookies = function() {
    document.write('<scr'+'ipt type="text/javascript" src="http://www.scenedaily.com/templates/determineLoginStatus.js?c=n"></scr'+'ipt>');
};

// If there is a UID cookie (means they should be logged in), but the loginStatus cookie not set yet, call setLoginCookies to initialize them
if ( readCookie("UID") && !readCookie("loginStatus") ) {
    setLoginCookies();
}

// If the UID cookie has gone away (means they have logged out), clear out their cookies so that they'll be set fresh upon next login
if ( !readCookie("UID") && readCookie("loginStatus") ) {
    eraseCookie("loginStatus");
}

// We need to de-conflict jQuery here since
// we're including Prototype too
jQuery.noConflict();

// creates the coda slider on the homepage
(function($) {    
    var theInt = null;
    var $crosslink, $navthumb;
    var curclicked = 0;

    theInterval = function(cur){
    	clearInterval(theInt);
	
    	if( typeof cur != 'undefined' )
    		curclicked = cur;
	
    	$crosslink.removeClass("active");
    	$navthumb.eq(curclicked).parent().addClass("active");
    		$(".stripNav ul li a").eq(curclicked).trigger('click');
	
    	theInt = setInterval(function(){
    		$crosslink.removeClass("active");
    		$navthumb.eq(curclicked).parent().addClass("active");
    		$(".stripNav ul li a").eq(curclicked).trigger('click');
    		curclicked++;
    		if( 5 == curclicked )
    			curclicked = 0;
		
    	}, 4000);
    };

    $(function(){
        if ( $("#primary-news-slider").length > 0 ) {
    	    $('#primary-news-slider').codaSlider();
    	}
    	//$("#promotions-slider").codaSlider();
	
    	$navthumb = $(".nav-thumb");
    	$crosslink = $(".cross-link");
	
    	$navthumb
    	.click(function() {
    		var $this = $(this);
    		theInterval($this.parent().attr('href').slice(1) - 1);
    		return false;
    	});
	
    	theInterval();
    });
})(jQuery);

(function($) {
    $().ready(function(){
        // adds the browser name and js to the homepage
        if($.browser.mozilla) {
            $("html").addClass("js mozilla");
        } else if($.browser.safari) {
            $("html").addClass("js safari");
        } else if($.browser.msie) {
            $("html").addClass("js msie");
        } else {
            $("html").addClass("js");
        }
        
        // Toggles the login or logout overlay for the header
        $("a#login-tab").toggle(
            function () { 
                $("#login-overlay").animate({top: "0px"}, 400);
                $(".down").addClass("up");
            }, 
            function () { 
                $("#login-overlay").animate({top: "-323px"}, 400);
                $(".down").removeClass("up");
            } 
    	);
    	$("a#logout-tab").toggle(
            function () { 
                $("#login-overlay").animate({top: "0px"}, 400);
                $(".down").addClass("up");
            }, 
            function () { 
                $("#login-overlay").animate({top: "-323px"}, 400);
                $(".down").removeClass("up");
            } 
    	);
                
        // popeye
        if ( $("#photo-slideshow").length > 0 ) {
            $('#photo-slideshow').popeye({
    			direction: 'left',
                stageW: '472px',
                stageH: '290px',
                easing: 'swing'
    		});
    	}
        
        // Stock cartoon, close-up and normal image gallery fancybox effect
        if ( $("#closeups .content  a").length > 0 ) {
            $('#closeups .content  a').fancybox();
        }
        if ( $("#stock-cartoon .content a").length > 0 ) {
            $('#stock-cartoon .content a').fancybox();
        }
        if ( $("#gallery ul li a").length > 0 ) {
            $('#gallery ul li a').fancybox();
        }
        if ( $("#lifestyle-gallery .content ul li a").length > 0 ) {
            $('#lifestyle-gallery .content ul li a').fancybox();
        }
		
        // Makes the tabs work
        if ( $(".tabs > ul").length > 0 ) {
            $(".tabs > ul").tabs();
        }

        if ( $("#video-gallery > ul").length > 0 ) {
            $("#video-gallery > ul").tabs({ fx: { opacity: 'toggle' } });
        }

        // Created the facebox popup
        if ( $('a[@rel*=facebox]').length > 0 ) {
            $('a[@rel*=facebox]').facebox();
        }

        // Places text from a title attribute into an input
        jQuery.fn.hint = function() {
            return this.each(function(){
                var t = $(this);
                var title = t.attr('title');

                if (title) {
                    t.focus(function(){
                        if (t.val() == title) {
                          t.val('');
                          t.removeClass('blur');
                        }
                    })

                    t.blur(function(){
                        if (t.val() == '') {
                          t.val(title);
                          t.addClass('blur');
                        }
                    })

                    t.parents('form:first()').submit(function(){
                        if (t.val() == title) {
                            t.val('');
                            t.removeClass('blur');
                        }
                    });

                    t.blur();
                }
            })
        }        
        // drops a hint in input fields
        $('input:text').hint();

        // Reset Font Size
        var originalFontSize = $('.resize-area').css('font-size');
        $(".reset-text").click(function(){
                $('.resize-area').css('font-size', originalFontSize);
        });

        // Increase Font Size
        $(".increase-text").click(function(){
            var currentFontSize = $('.resize-area').css('font-size');
            var currentFontSizeNum = parseFloat(currentFontSize, 10);
            var newFontSize = currentFontSizeNum*1.1;
            $('.resize-area').css('font-size', newFontSize);
            return false;
        });

        // Decrease Font Size
        $(".decrease-text").click(function(){
            var currentFontSize = $('.resize-area').css('font-size');
            var currentFontSizeNum = parseFloat(currentFontSize, 10);
            var newFontSize = currentFontSizeNum*0.9;
            $('.resize-area').css('font-size', newFontSize);
            return false;
        });

        // Open new window for external links
        $("a[rel='external']").attr('target', '_blank');
            
        // Validations
        //Login in the dropdown thats on every page
        if ( $('#login form').length > 0 ) {
            $("#login form").validate({
            	rules: {
            		email: {
            			required: true,
            			email: true
            		},
            		password: {
            			required: true,
            			minlength: 6
            		}
            	},
            	messages: {
            	    email: {
            	        required:       "You can't leave your email blank",
            	        email:          "Must use a valid email address"
            	    },
                    password: {
                        required:       "You can't leave your password blank",
                        minlength:            "Your password must be at least 6 characters"
                    }
            	}
            });
        }
        
        // Login page for comments
        if ( $('#comment-login').length > 0 ) {
            $("#comment-login").validate({
            	rules: {
            		email: {
            			required: true,
            			email: true
            		},
            		password: {
            			required: true,
            			minlength: 6
            		}
            	},
            	messages: {
            	    email: {
            	        required:       "You can't leave your email blank",
            	        email:          "Must use a valid email address"
            	    },
                    password: {
                        required:       "You can't leave your password blank",
                        minlength:            "Your password must be at least 6 characters"
                    }
            	}
            });
        }
        // Posting a comment
        if ( $('#comment-form').length > 0 ) {
            $("#comment-form").validate({
            	rules: {
            		field: {
            			required: true
            		}
            	},
            	messages: {
            	    field: "You didn't add in any comments."
            	},
            	submitHandler: function(form){
            	    insertComment(document.getElementById('comment-form'))
            	}
            });
        }
        if ( $('textarea#commentFormComment').length > 0 ) {
            $('textarea#commentFormComment').keyup(function() {
                var charLength = $(this).val().length;
            
                // Displays count
                $('span#char-count').html('(' + charLength + '\/2000 characters left)');
            
                // Alerts when 2000 characters is reached
                if($(this).val().length > 2000)
                    $('span#char-count').html('You may only have up to 2000 characters.');
            });
        }
        
        // Comment live preview
        // Creates the live preview box
        //var $previewHTML = '';
        
        //$('#comment-form textarea').one("focus",function() {
        //    $(this).parent().after( $previewHTML );
            //$("#preview-box").fadeIn("slow");
        //});
        
        var $comment = '';
        
        if ( $('#comment-form textarea').length > 0 ) {
            $('#comment-form textarea').keyup(function() {
                $comment = $(this).val();
                $comment = $comment.replace(/\n/g, "<br />")
                .replace(/\n\n+/g, '<br /><br />');
                $('#live-preview').html( $comment );
            });
            }
        
        if ( $('#top-tools .share').length > 0 ) {
            $("#top-tools .share").hover(
                function () { 
                    $("#top-tools .share").addClass("selected")
                }, 
                function () { 
                    $("#top-tools .share").removeClass("selected")
                } 
            );
        }
        if ( $('#bottom-tools .share').length > 0 ) {
            $("#bottom-tools .share").hover(
                function () { 
                    $("#bottom-tools .share").addClass("selected")
                }, 
                function () { 
                    $("#bottom-tools .share").removeClass("selected")
                } 
            );
        }
        
        // Creates the print button to make it unobtrusive
        if ( $('ul.tools li.rss').length > 0 ) {
            $('ul.tools li.rss').after('<li class="print"><a href="#print">Print this Article</a></li>');
        }
        if ( $('ul.tools li.print a').length > 0 ) {
            $('ul.tools li.print a').click(function() {
                window.print();
                return false;
            });
        }

        // removes classes so we can override them
        if ( $('link#theport_customcss').length > 0 ) {
            $('link#theport_customcss').remove();
        }
        if ( $('link#theport_headercss').length > 0 ) {
            $('link#theport_headercss').remove();
        }
    });
})(jQuery);
