$(document).ready(function( ) {
    /* Vars */
//    var root = 'http://' + window.location.hostname + '/';
    var root = 'http://www.ecomparison.co.uk/';
    var browser = navigator.appVersion;
    
    /* Home Page and Generics */

    //Comparison Menu
    $('.menu-slice-right').click( function() {
	// Identify Popup
	var id = $(this).attr( "id" );
	id = id.replace( "menu-", "" );

	// Find Left Val
	switch( id )
	{
	    case 'comp':
		var left = 58;
	    break;

	    case 'cash':
		var left = 178;
	    break;

	    case 'vouc':
		var left = 284;
	    break;
	}

	// Set Margin Left
	$("#menu-" + id + "-popup").css( 'margin-left', left + "px" );
	$("#" + id + "-pop-shadow").css( 'margin-left', ( left + 5 ) + "px" );

	if( $("#" + id + "-pop-shadow").css('display') == 'none' )
	{
	    $(".menu-popup").hide();
	    $(".pop-shadow").hide();

	    $(".menu-slice-right").each(function(){
		// Set Selected Var
		var selected	= ( $(this).attr("src").indexOf("-selected") >= 0 )
				? "-selected"
				: "";
		$(this).attr( "src", root + 'images/site/header/menu/right-off' + selected + '.gif' );
	    });
	}

	// Flick Popup and Shadow On
	$("#" + id + "-pop-shadow").toggle();
	$("#menu-" + id + "-popup").toggle();

	// Set Selected Var
	var selected	= ( $(this).attr("src").indexOf("-selected") >= 0 )
			? "-selected"
			: "";

	// Set Updated Src
	if ( $(this).attr("src").indexOf("-off") >= 0 )
	{
	    $(this).attr( "src", root + 'images/site/header/menu/right-on' + selected + '.gif' );
	} else {
	    $(this).attr( "src", root + 'images/site/header/menu/right-off' + selected + '.gif' );
	}
    });

    $('.menuclose').click( function() {
        // Identify Popup
	var id = $(this).parent("div").attr( "id" );
	id = id.replace( "menu-", "" );
	id = id.replace( "-popup", "" );

	// Flick Popup and Shadow On
	$("#" + id + "-pop-shadow").toggle();
	$("#menu-" + id + "-popup").toggle();

	// Set Selected Var
	var selected	= ( $("#menu-" + id).attr("src").indexOf("-selected") >= 0 )
			? "-selected"
			: "";

	// Set Updated Src
	if ( $("#menu-" + id).attr("src").indexOf("-off") >= 0 )
	{
	    $("#menu-" + id).attr( "src", root + 'images/site/header/menu/right-on' + selected + '.gif' );
	} else {
	    $("#menu-" + id).attr( "src", root + 'images/site/header/menu/right-off' + selected + '.gif' );
	}
    });

    //Search Clearing on input
    $('#searchInput').click( function() {
        if( $(this).val() == 'Enter a brand eg. Argos, Dixons' )
        {
            $(this).val( '' );
        }
    });

    //category popup
    $('#searchCat').click( function() {
        if ($("#catPop").is(":hidden")) {
            $("#catPop").slideDown("fast");
        } else {
            $("#catPop").hide();
        }
    });

    //category close button
    $('#catPop .close').click( function() {
        $("#catPop").hide();
    });

    //gallery homepage
    window.api = $(".scrollable").scrollable().autoscroll({
        autoplay: true
    }).circular();

    $('.quotePop').click(function( )
    {
        window.open( this.href, "mywindow","location=0,status=0,scrollbars=1,width=1000,height=800" );
        return false;
    });
    
    /* EndOf Home Page and Generics */



    /* RETAILERS BREAK * /



    /* Retailers JS */
    if( browser.indexOf( 'MSIE 6.0' ) != -1 )
    {
        var width = $('#banner img').width( );
        var height = $('#banner img').height( );

        if( width > 625 )
        {
            var multiplier = width / 625;
            var newWidth = 625;
            var newHeight = Math.ceil( height / multiplier );

            $('#banner img').width( newWidth );
            $('#banner img').height( newHeight );
        }
    }

    // VOUCHER CODE REVEAL
    $('a.voucherPop').hover( function() {
        var voucherid = $(this).attr("id").split("-");
        var vouchercode = $(this).attr("name");
        var check = false;
        $(this).find('img').each( function() {
            $(this).remove();
            check = true;
        });

        if( check )
        {
            $(this).find('input').each( function() {
                $(this).remove();
            });
            var text = '<input class="voucher-code spoiler" value="' + vouchercode + '" />';
            $(this).append(text);
        }
    }, function() {
        var voucherid = $(this).attr("id").split("-");
        var check = false;
        $(this).find('input.spoiler').each( function() {
            $(this).remove();
            check = true;
        });

        if( check )
        {
            $(this).find('img').each( function() {
                $(this).remove();
            });
            var img = '<img id="hb-' + voucherid[1] + '" src="' + root + 'images/voucher/hover-to-reveal-code.gif" width="205" height="26" alt="Click to Copy Code and Launch Website" title="Click to Copy Code and Launch Website" style="border: 2px solid #DFDFDF; margin: 0px; padding: 0px;" />';
            $(this).append(img);
        }
    });

    $('a.voucherPop').click( function() {
        var voucherid = $(this).attr("id").split("-");
        var ext = '-' + voucherid[2] + '-';
        var vouchercode = $(this).attr("name");
        var text = '<input class="voucher-code spoiler" value="' + vouchercode + '" />';
        $(this).parent().append( text );
        $(this).parent().find('.spoiler').css( 'cursor', 'text' );

        var href = $(this).attr( 'href' );

        $('#vp-' + voucherid[1] + ext + 'vp').show();

        $(this).remove();

        winpop = window.open($(this).attr("href"),'_blank','toolbar=1,location=1,directories=1,status=1,menubar=1,scrollbars=1,resizable=1');
        winpop.blur();

        var thanks = '<div class="voucher-help-single">' +
                    '<div>' +
                    '<p>To use this voucher code, enter when you get to the checkout, If you are having problems with the pop up window? ' +
                    '<a href="' + href + '">' +
                    'Click here to go directly to the web site</a></p>' +
                    '</div></div>';
        console.log( thanks );

        $('#th-' + voucherid[1]).after(thanks);

        return false;
    });


    $('a.extVoucherPop').click( function() {
        var voucherid = $(this).attr("id").split("-");
        var ext = '-' + voucherid[2] + '-';
        var href = $(this).attr("href");

        var vouchercode = $('a#h-' + voucherid[1] + ext + 'h').attr("name");

        var text = '<input class="voucher-code spoiler" value="' + vouchercode + '" />';
        $('a#h-' + voucherid[1] + ext + 'h').parent().append( text );
        $('a#h-' + voucherid[1] + ext + 'h').parent().find('.spoiler').css( 'cursor', 'text' );

        $('a#h-' + voucherid[1] + ext + 'h').remove();

        $('#vp-' + voucherid[1] + ext + 'vp').show();

        winpop = window.open($(this).attr("href"),'_blank','toolbar=1,location=1,directories=1,status=1,menubar=1,scrollbars=1,resizable=1');
        winpop.blur();
        
        var thanks = '<div class="voucher-help-single">' +
                    '<div>' +
                    '<p>To use this voucher code, enter when you get to the checkout, If you are having problems with the pop up window? ' +
                    '<a href="' + href + '">' +
                    'Click here to go directly to the web site</a></p>' +
                    '</div></div>';
        console.log( thanks );
        
        $('#th-' + voucherid[1]).after(thanks);

        return false;
    });

    $("editPost").submit(function() {
        $.post("test.php", function(data){
            alert("Data Loaded: " + data);
            return false;
        });

        return false;
    });

    $("#email-add-field").focus(function () {
        if ( $('#email-add-field').val() == 'Please enter your email address' )
        {
            $('#email-add-field').val('');
        }
    });

    $("#email-add-field").blur(function () {
        if ( $('#email-add-field').val() == '' )
        {
            $('#email-add-field').val('Please enter your email address');
        }
    });

    $("#email-add-click").click(function() {

        var email 		= $("input#email-add-field").val();
        var merchantid 	= $("input#merchantid").val();

        if ( email == '' )
        {
            $('#h1-email-add').text('Email Address Problem');
            $('#email-add-text').text('Sorry! There seems to be a problem with the email address you have entered. Please close this window and try again...');

        } else {

            var regex = new RegExp("^[0-9a-z\\._]+@[0-9a-z]+\\..+$","i");

            if (regex.test(email))
            {
                var dataString = 'email=' + email + '&merchantid=' + merchantid;

                $('#h1-email-add').text('Email Address Added');
                $('#email-add-text').text('Thanks! We have added your email address to our database and we will let you know when any new offers or voucher codes are available.');

                //alert (dataString); return false;

                $.ajax({
                    type: "POST",
                    url: "add-email/",
                    data: dataString,
                    success: function() {

                    }
                });

                $('.email-alert').slideToggle( );


            } else{
                $('#h1-email-add').text('Email Address Problem');
                $('#email-add-text').text('Sorry! There seems to be a problem with the email address you have entered. Please close this window and try again...');
            }
        }
    });


    $(".tellafriend").click(function() {
        var voucherid = $(this).attr("id").split(":");
        $('#voucherid').attr( "value", voucherid[1] );
    });


    $(".formSubmit").click(function() {
        var name 			= $("input#name").val();
        var email 			= $("input#emailfield").val();
        var friendemail1 	= $("input#friendmail1").val();
        var friendemail2 	= $("input#friendmail2").val();
        var friendemail3 	= $("input#friendmail3").val();
        var merchantid 		= $("input#merchantid").val();
        var voucherid 		= $("input#voucherid").val();

        if ( name != '' && email != '' && friendemail1 != '' )
        {
            var dataString = 'name='+ name + '&emailfield=' + email + '&friendemail1=' + friendemail1 + '&friendemail2=' + friendemail2 + '&friendemail3=' + friendemail3 + '&merchantid=' + merchantid + '&voucherid=' + voucherid;
            //alert (dataString);return false;

            $.ajax({
                type: "POST",
                url: "tell-a-friend/",
                data: dataString,
                success: function() {
                    $('#email-friend-content-dynamic').html("<p>Thank for telling a friend about eComparison, a message has been sent to the friends email addresses you entered.");
                }
            });

            return false;
        }
    });

    $('#merchantProfile .thickbox').click( function() {
        /*
                 *  i.      set countdown of timer
                 *  ii.     redirect after 10
                 *  iii.    cancel redirect if closed
                 */

        // i.      set countdown of timer
        var cTicks = $('#countMe').html();
        cTicks = parseInt( cTicks );

        var timer = setInterval(function()
        {
            if( cTicks )
            {
                $('#countMe').html(cTicks--);
            } else {

                clearInterval( timer );

                // give it 5 seconds before reset to 10
                var timeReset = setTimeout( function() {
                    $('#countMe').html('15');
                }, 5000 );

            }
        }, 1000);

        // ii.     redirect after 10
        if( $("#redirUrl").attr('href') )
        {
            var timeout = setTimeout( function() {

                //iii.    cancel redirect if closed
                if( $('#TB_ajaxContent').css('display') == 'block' )
                {
                    document.location = $("#redirUrl").attr('href');
                }
            }, 15000 );

            return false;
        }
    });
});




/**
 * --------------------------------------------------------------------
 * jQuery-Plugin "pngFix"
 * Version: 1.1, 11.09.2007
 * by Andreas Eberhard, andreas.eberhard@gmail.com
 *                      http://jquery.andreaseberhard.de/
 *
 * Copyright (c) 2007 Andreas Eberhard
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 *
 * Changelog:
 *    11.09.2007 Version 1.1
 *    - removed noConflict
 *    - added png-support for input type=image
 *    - 01.08.2007 CSS background-image support extension added by Scott Jehl, scott@filamentgroup.com, http://www.filamentgroup.com
 *    31.05.2007 initial Version 1.0
 * --------------------------------------------------------------------
 * @example $(function(){$(document).pngFix();});
 * @desc Fixes all PNG's in the document on document.ready
 *
 * jQuery(function(){jQuery(document).pngFix();});
 * @desc Fixes all PNG's in the document on document.ready when using noConflict
 *
 * @example $(function(){$('div.examples').pngFix();});
 * @desc Fixes all PNG's within div with class examples
 *
 * @example $(function(){$('div.examples').pngFix( { blankgif:'ext.gif' } );});
 * @desc Fixes all PNG's within div with class examples, provides blank gif for input with png
 * --------------------------------------------------------------------
 */

(function($) {

jQuery.fn.pngFix = function(settings) {

	// Settings
	settings = jQuery.extend({
		blankgif: 'blank.gif'
	}, settings);

	var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
	var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);

	if (jQuery.browser.msie && (ie55 || ie6)) {

		//fix images with png-source
		jQuery(this).find("img[@src$=.png]").each(function() {

			jQuery(this).attr('width',jQuery(this).width());
			jQuery(this).attr('height',jQuery(this).height());

			var prevStyle = '';
			var strNewHTML = '';
			var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : '';
			var imgClass = (jQuery(this).attr('class')) ? 'class="' + jQuery(this).attr('class') + '" ' : '';
			var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : '';
			var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : '';
			var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : '';
			var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : '';
			if (this.style.border) {
				prevStyle += 'border:'+this.style.border+';';
				this.style.border = '';
			}
			if (this.style.padding) {
				prevStyle += 'padding:'+this.style.padding+';';
				this.style.padding = '';
			}
			if (this.style.margin) {
				prevStyle += 'margin:'+this.style.margin+';';
				this.style.margin = '';
			}
			var imgStyle = (this.style.cssText);

			strNewHTML += '<span '+imgId+imgClass+imgTitle+imgAlt;
			strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;'+imgAlign+imgHand;
			strNewHTML += 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;';
			strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(this).attr('src') + '\', sizingMethod=\'scale\');';
			strNewHTML += imgStyle+'"></span>';
			if (prevStyle != ''){
				strNewHTML = '<span style="position:relative;display:inline-block;'+prevStyle+imgHand+'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;'+'">' + strNewHTML + '</span>';
			}

			jQuery(this).hide();
			jQuery(this).after(strNewHTML);

		});

		// fix css background pngs
		jQuery(this).find("*").each(function(){
			var bgIMG = jQuery(this).css('background-image');
			if(bgIMG.indexOf(".png")!=-1){
				var iebg = bgIMG.split('url("')[1].split('")')[0];
				jQuery(this).css('background-image', 'none');
				jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
			}
		});

		//fix input with png-source
		jQuery(this).find("input[@src$=.png]").each(function() {
			var bgIMG = jQuery(this).attr('src');
			jQuery(this).get(0).runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + bgIMG + '\', sizingMethod=\'scale\');';
   		jQuery(this).attr('src', settings.blankgif)
		});

	}

	return jQuery;

};

})(jQuery);

$(document).ready(
	function( )
	{
		$(document).pngFix( );
	}
);


/* FAVOURITES PLUGIN */
function bookPage() {
    if (window.sidebar)
    { // Mozilla Firefox Bookmark
            window.sidebar.addPanel(document.title, location,"");
    } else if (document.all)
    {
            window.external.AddFavorite(location,document.title);
    }
    return false;
}

