//This will changed when pushed live.  It is to accmodate the testing environment
//Leave of trailing slash!!!!!!!!!!!!
var sHomeDomain = "http://www.speedtv.com";
var search_sug = sHomeDomain + "/search_sug/sug.php";
function stripslashes (str) {
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +      fixed by: Mick@el
    // +   improved by: marrtins
    // +   bugfixed by: Onno Marsman
    // +   improved by: rezna
    // +   input by: Rick Waldron
    // +   reimplemented by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: stripslashes('Kevin\'s code');
    // *     returns 1: "Kevin's code"
    // *     example 2: stripslashes('Kevin\\\'s code');
    // *     returns 2: "Kevin\'s code"
    return (str+'').replace(/\\(.?)/g, function (s, n1) {
        switch (n1) {
            case '\\':
                return '\\';
            case '0':
                return '\0';
            case '':
                return '';
            default:
                return n1;
        }
    });
}

function replaceSubstring(exp, str, wit) { 
    
    var sSplit = exp.split(str);
    var sFinal = sSplit.join(wit);
    
    
    return sFinal;
};

var toggleLoggedIn = function (e) {
    
    var myDiv = jQuery("#u_login");
    var myTxt = jQuery(".u_logged_in_txt");
    
    //Make sure the event is in the area of interest
    if ((e.target != myDiv[0]) && (e.target != myTxt[0]) && (e.target != "strong")) return  true;
    
    jQuery("#u_flyout_li").slideToggle("fast");
    jQuery("#u_login").toggleClass("u_on");
    jQuery("#u_login").toggleClass("u_off");
};

var toggleLogin = function (e) {
    var myDiv = jQuery("#u_login");
    var myTxtOff = jQuery(".u_login_text_off");
    var myTxtOn = jQuery(".u_login_text_on");
    
    if ((e.target != myDiv[0]) && (e.target != myTxtOff[0]) && (e.target != myTxtOn[0])) return  true;
    
    jQuery("#u_flyout").slideToggle("fast");
    jQuery("#u_login").toggleClass("u_on");
    jQuery("#u_login").toggleClass("u_off");
    jQuery(".u_login_text_off").toggle();
    jQuery(".u_login_text_on").toggle();
    
   	// Bind Enter key to form submit for this input field
	jQuery( '#u_login_username' ).keyup(
	    function( e )
	    {
    	    if( e.keyCode == 13 )
        	{
				jQuery("form[name='member_login_form']").submit();
    	    }
	    }
    );

	// Bind Enter key to form submit for this input field    	
	jQuery( '#u_login_pass' ).keyup(
	    function( e )
	    {
    	    if( e.keyCode == 13 )
        	{
				jQuery("form[name='member_login_form']").submit();
    	    }
	    }
    );   	    	    
};

var toggleNOS = function (e) {
    
    var myDiv = jQuery("#now_playing");
    var myTxt = jQuery("#now_playing .title");
    
    //Make sure the event is in the area of interest
    if ((e.target != myDiv[0]) && (e.target != myTxt[0])) return  true;
    jQuery("#nos_flyout").slideToggle("fast");
    jQuery("#now_playing").toggleClass("nos_on");
    jQuery("#now_playing").toggleClass("nos_off");
    
};
var fNOScb = function(data, textStatus) {
    var sDec = stripslashes(data.nos_ret);
    jQuery(".header_toolbar #now_playing").html(sDec);
    jQuery("#nos_flyout").ready(function() {
        jQuery("#now_playing").bind("click",toggleNOS);
    });
};
var fUserCB = function (data, textStatus) {

    jQuery(".header_toolbar #u_login").html(data.ret_html);
    var LoggedIn = jQuery("#u_flyout_li");
    
    if ((LoggedIn === undefined) || (LoggedIn.length < 1)) {
        jQuery("#u_login_pass").ready(function() {
                                                    jQuery("#u_login_pass").keypress(function () {
                                                        if (jQuery("#u_login_pass").attr('value') != '' ){
                                                            jQuery("#u_login_pass_bg").html('');
                                                        } else {
                                                            jQuery("#u_login_pass_bg").html('Password');
                                                        }
                                                    });
                                                    jQuery("#u_login_pass").blur(function () {
                                                        var foo = jQuery("#u_login_pass");
                                                        var pass = foo.attr('value');
                                                        if ((pass !== undefined) && (pass != '' )){
                                                            jQuery("#u_login_pass_bg").html('');
                                                        } else {
                                                            jQuery("#u_login_pass_bg").html('Password');
                                                        }
                                                    });
                                                    var reg = /[/]/g;
                                                    var wURL = document.location.href.substring(0);
                                                    var hInput = jQuery("#u_login div.hiddenFields input[name='RET']");
                                                    if ((hInput !== undefined) && (hInput.length == 1)) {
                                                        //we have the form return value, now set it to the current URI.
                                                        if (wURL.toLowerCase().indexOf('my.speedtv.com') == -1)
                                                            sVal1 = replaceSubstring(wURL, "/", '&#47;');
                                                        else
                                                            sVal1 = 'http:&#47;&#47;my.speedtv.com&#47;';
                                                        hInput.val(sVal1);
                                                    }
                                                    
         });
        jQuery("#u_login").bind("click", toggleLogin);
    } else {
        jQuery("#u_login").bind("click", toggleLoggedIn);
    }
};
var fFormatItem = function(row, pos, total, search) {
    pieces = row[0].split('@@@');
    if (pieces.length == 3) {
        //This is a keyword match
        ret = '<div class="searchKeywordLabel">'+pieces[2]+'</div><a href="'+pieces[0]+'" class="searchKeyword">'+pieces[1]+'&nbsp;&rsaquo;&rsaquo;</a>';
    } else if (pieces.length == 1) {
        //This is standard suggest
        ret = '<a href="'+ sHomeDomain + '/search/google/'+escape(pieces[0])+'" class="searchSug">' + pieces[0] + '</a>';
    } else {
        //Don't know...just pass it through
        ret = row;
    }
    
    return ret;
};

jQuery(document).ready(function () {
    var d = new Date();
    var gmtHours = d.getTimezoneOffset()/60;

    jQuery.getJSON(sHomeDomain + "/ajax/nos/"+gmtHours+"/?callback=?", {}, fNOScb); 
    jQuery.getJSON(sHomeDomain + "/ajax/my_speed_details/?callback=?", {}, fUserCB);

    //jQuery("#txtQuery").keydown(checkEnter);
    
    oOptions = {
        max: 7,
        minChars: 2,
        highlight: false,
        scroll: false,
        width: 254,
        selectFirst: false,
        cacheLength: 0,
        dataType: 'jsonp',
        formatItem: fFormatItem,
        formatResult: function(data,pos,total) { return 'Thank You!';},
        highlight: function(value, term) {
            return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), '<span class="ac_match">$1</span>');
        }
    };
    jQuery("#txtQuery").autocomplete(search_sug, oOptions);
    jQuery('#txtQuery').result(function(event, data, formatted) {
            pieces = data[0].split('@@@');
            if (pieces.length == 3) {
                //This is a keyword match
                window.location=pieces[0];
            } else if (pieces.length == 1) {
                //This is standard suggest
                window.location=sHomeDomain + '/search/google/'+escape(pieces[0]);
            } 
        });
});

function checkEnter(e){ //e is event object passed from function invocation
    var characterCode; //literal character code will be stored in this variable

    if(e.which == 13){ //if generated character code is equal to ascii 13 (if enter key)
        google_search(); //submit the form
        event.stopImmediatePropagation();
        return false;
    }
    else{
        return true;
    }
}