$(document).ready(function() 
{
     var root = 'http://' + window.location.hostname + '/';
     $("#phone").autocomplete( root + "suggest/", {
            width: 292,
            max: 100,
            highlight: false,
            scroll: true,
            scrollHeight: 405,
            formatItem: function(data, i, n, value) {
                    val = value;
                    val = val.replace( '#', '');
                    val = val.replace( '#', '');
                    return val;
            },
            formatResult: function(data, value) {
                    val = value.split("#")[1];
                    return val;
            }
    });
     
//    $("table#results").tablesorter({ 
//        headers: { 
//            0: { sorter: false }, 
//            4: { sorter: false },
//            5: { sorter: false },
//            6: { sorter: false },
//            7: { sorter: false }
//        },
//        sortList: [[1,1]],
//        cssAsc: 'headerSortAsc',
//        cssDesc: 'headerSortDesc'
//    }); 

    $("#phone").result(function(event, data, formatted) {
        var redirect = $(data + ' span').html();
        window.location = root + 'phone/' + redirect + '/';
    });

    $("#phone").focus( function () {
        if( $(this).val() == 'Enter your make/model, eg. nokia n95' ) {
            $(this).val('').css('color','#4E4E50');
        }
    }, function() {
    	if( $(this).val() == '' || $(this).val() == ' ' ) {
            $(this).val('Enter your make/model, eg. nokia n95').css('color','#D2D2D2');
        }
    });

    //tab flick
    var tabContainers = $('div.stats-tabs > div');
    $('div.stats-tabs ul.tabNav a').click(function () {
        tabContainers.hide().filter(this.hash).show();

        $('div.stats-tabs ul.tabNav a').removeClass('selected');
        $(this).addClass('selected');

        //remove any current 'ons'
        $.each( $('div.stats-tabs ul.tabNav img'), function( ) {
            var src = $(this).attr('rel');
            $(this).attr('src', '/images/stats/' + src + '.gif' );
        });

        //add ons!
        var rel = $(this).find('img').attr('rel');
        $(this).find('img').attr('src', '/images/stats/' + rel + '_on.gif' );

        return false;
    });

    // popup upon clicking result
    var showFancy = true;
    $("a.outbound").click( function() {
        if( showFancy == true )
        {
            $('.fancy').fancybox({
            'frameHeight': 205,
            'hideOnContentClick' : false,
            'callbackOnShow': callbacknewsletter
            }).trigger( 'click' );
        }
        showFancy = false;
    });

    function callbacknewsletter( ) {
        $(".newsletterpop").submit( function()
        {
            var emailnews = $(this).find("#emailnews").val();
            
            if( trim( emailnews ) != '' )
            {
                if( trim( emailnews ) != 'enter your e-mail address' )
                {
                    var match = new RegExp (/^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/);
                    if( !match.test( emailnews ) )
                    {
                        alert( "You have not entered a valid e-mail address" );
                    } else {
                        $.ajax({
                            type: "POST",
                            url: root + "submitEmail/",
                            data: "email=" + emailnews,
                            dataType: 'html',
                            success: function( msg )
                            {
                                $('#fancy_div form').html( "<h3>Thank you!</h3><p>Thanks for subscribing to our newsletter, we have sent an email to your address to confirm subscription</p>" );
                            }
                        });
                    }
                }
            }
            return false;
        });
    }

    // force second tab click
    //$('.tabNav a:eq(1)').click();

    // click the hash if set
    var hash = window.location.hash;
    if( hash.indexOf("tab") != -1 )
    {
        $(hash).click();
    }

    //click tabs if on same page
    $('li.floatr a').click( function() {
        if( $(this).attr('href').indexOf("tab") != -1 )
        {
            var string = $(this).attr('href').split('#');
            $('#' + string[1]).click();
        }
    });


    // Newsletter Subscribe / E-mail Catcher
    $("input#email").focus( function(){
	if( $(this).val( ) == "enter your e-mail address" )
	{
		$(this).val( "" );
	}
	$(this).css( "color", "#666" );
    });

    $("input#email").blur( function(){
	if( trim( $(this).val( ) ) == "" )
	{
		$(this).val( "enter your e-mail address" );
		$(this).css( "color", "#BBBBBB" );
	}
    });

    
    // newsletter signup for site (not popup)
    $("form#newsletter").submit( function(){
	if( trim( $(this).find("#email").val() ) != '' )
	{
	    if( trim( $(this).find("#email").val() ) != 'enter your e-mail address' )
	    {
		var match = new RegExp (/^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/);
		if( !match.test( $("input#email").val( ) ) )
		{
		    alert( "You have not entered a valid e-mail address" );
		} else {
		    $.ajax({
			type: "POST",
			url: "submitEmail/",
			data: "email=" + $("input#email").val( ),
			dataType: 'html',
			success: function( msg )
			{
			    // Write the thank you message
			    var fontsize = ( msg == 'Thanks for subscribing to our newsletter.' ) ? "12" : "11";
			    var thanks = '<p id="thanks" style="font-size: ' + fontsize + 'px; padding: 5px; margin: 0px 5px; font-weight: bold; display: none; background-color: #D3F289;">' + msg + '</p>';

			    // Prepend the thank you message
			    $("form#newsletter").parent().append( thanks );

			    // Remove the form
			    $("form#newsletter").slideToggle( "fast" );

			    // Perform the crazy Jonesy blend
			    $("#thanks").fadeIn( 500 ).animate({ backgroundColor: '#FFF0E4' }, 1000);
		       }
		    });
		}
	    }
	}
	return false;
    });


    //gallery homepage
    window.api = $(".scrollable").scrollable().autoscroll({
        autoplay: true
    }).circular();

    //confirm
    $('.confirm').click( function() {
       var answer = confirm( 'Are you sure you want to Sign out?' );
       if( !answer ) {
           return false;
       }
    });

    $('.del').click( function() {
       var answer = confirm( 'Are you sure you want to Delete this alert?' );
       if( !answer ) {
           return false;
       }
    });


    //date picker
    $(".datepicker").datepicker( {
        yearRange: '2009:2020',
        showOn: 'both',
        buttonImage: '/images/calender.gif',
        buttonImageOnly: true,
        dateFormat: 'dd/mm/yy'
    });



    //LIVE update!
    function liveUpdate( )
    {
        //only run this script on root homepage
        if(window.location.pathname == '/' || window.location.pathname == '/all-recent/' )
        {
            //set interval for function
            setInterval( function() {
                var response = $.ajax({
                    url: root + "liveUpdate/",
                    dataType: "text",
                    success: function(response)
                    {
                        // parse response of ajax call
                        var phones = response.split("\n");

                        //for each result parse
                        for ( var c in phones )
                        {
                            // split variables for individual phone and create master var
                            var phone = phones[c].split( '::' );

                            //check to see if phone exists already, if not add it!
                            if( $("#items li[rel='" + phone[0] + "#" + phone[1] + "']").length == 0 )
                            {
                                // set count variables
                                var n = $("#items li:first-child").attr("id");
                                var v = parseInt( n.split('item')[1] );
                                var b = (v+1);
                                var m = (v-2);
                                var height = ( window.location.pathname == '/all-recent/' ) ? '44' : '30';

                                //build the li
                                var li = '<li style="display: none; background-color: #D3F289;" id="item' + b + '" rel="' + phone[0] + '#' + phone[1] + '">' +
                                         '<img src="' + root + 'images/merchants_mini/' + phone[2] + '.gif" height="' + height + '" alt="' + phone[3] + '" class="recentLogo" />' +
                                         '<div class="recentName">' +
                                         '<strong>' + phone[4] + '</strong>' +
                                         '<p>' + phone[5] + '</p>' +
                                         '</div>' +
                                         '<span>£' + phone[6] + '</span>' +
                                         '</li>';

                                //append it to the ul
                                $('#items').prepend( li );

                                //blend it in!
                                $('#item' + b).fadeIn( 1000 ).animate({ backgroundColor: '#F4F4F4' }, 500);

                                //remove the old!
                                if( window.location.path != '/all-recent/')
                                {
                                	$("#item" + m).remove( );
                                }
                            }
                        }
                    }
               });
            }, 10000 );
        }
        // above 10 second loop retry
    }
    // execute the function
    liveUpdate();

    $('#right_brands').corner("10px");
    $('#footer').corner("5px");
    $('.rightBox').corner("10px");
    $('.stats-tabs').corner("bottom 10px");
    $("#subHeader").corner("bottom 5px");

    $('.popThis').popupWindow({
        height:500,
        width:800,
        top:50,
        left:50,
        scrollbars:1
    });
});

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

/*
 * Jquery Window Popup
 */
(function($){
	$.fn.popupWindow = function(instanceSettings){

		return this.each(function(){

		$(this).click(function(){

		$.fn.popupWindow.defaultSettings = {
			centerBrowser:0, // center window over browser window? {1 (YES) or 0 (NO)}. overrides top and left
			centerScreen:0, // center window over entire screen? {1 (YES) or 0 (NO)}. overrides top and left
			height:500, // sets the height in pixels of the window.
			left:0, // left position when the window appears.
			location:0, // determines whether the address bar is displayed {1 (YES) or 0 (NO)}.
			menubar:0, // determines whether the menu bar is displayed {1 (YES) or 0 (NO)}.
			resizable:0, // whether the window can be resized {1 (YES) or 0 (NO)}. Can also be overloaded using resizable.
			scrollbars:0, // determines whether scrollbars appear on the window {1 (YES) or 0 (NO)}.
			status:0, // whether a status line appears at the bottom of the window {1 (YES) or 0 (NO)}.
			width:500, // sets the width in pixels of the window.
			windowName:null, // name of window set from the name attribute of the element that invokes the click
			windowURL:null, // url used for the popup
			top:0, // top position when the window appears.
			toolbar:0 // determines whether a toolbar (includes the forward and back buttons) is displayed {1 (YES) or 0 (NO)}.
		};

		settings = $.extend({}, $.fn.popupWindow.defaultSettings, instanceSettings || {});

		var windowFeatures =    'height=' + settings.height +
								',width=' + settings.width +
								',toolbar=' + settings.toolbar +
								',scrollbars=' + settings.scrollbars +
								',status=' + settings.status +
								',resizable=' + settings.resizable +
								',location=' + settings.location +
								',menuBar=' + settings.menubar;

				settings.windowName = this.name || settings.windowName;
				settings.windowURL = this.href || settings.windowURL;
				var centeredY,centeredX;

				if(settings.centerBrowser){

					if ($.browser.msie) {//hacked together for IE browsers
						centeredY = (window.screenTop - 120) + ((((document.documentElement.clientHeight + 120)/2) - (settings.height/2)));
						centeredX = window.screenLeft + ((((document.body.offsetWidth + 20)/2) - (settings.width/2)));
					}else{
						centeredY = window.screenY + (((window.outerHeight/2) - (settings.height/2)));
						centeredX = window.screenX + (((window.outerWidth/2) - (settings.width/2)));
					}
					window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
				}else if(settings.centerScreen){
					centeredY = (screen.height - settings.height)/2;
					centeredX = (screen.width - settings.width)/2;
					window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
				}else{
					window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + settings.left +',top=' + settings.top).focus();
				}
				return false;
			});

		});
	};
})(jQuery);
