// Required to fix IE problems with css('background-position') == undefined
jQuery.fn.backgroundPosition = function() {
    var p = this.css('background-position');
    if(typeof(p) === 'undefined') return this.css('background-position-x') + ' '+ this.css('background-position-y');
    else return p;
}

jQuery.fn.setBackgroundPosition = function(str) {
    var p = this.css('background-position');

    if(typeof(p) === 'undefined'){
        bgArray = str.split(" ");
        if(bgArray[0] !== "auto") this.css('background-position-x', bgArray[0]);
        if(bgArray[1] !== "auto") this.css('background-position-y', bgArray[1]);
    }else{
        this.css('background-position', str);
    }
}

jQuery(document).ready(function($) {

    // $() will work as an alias for jQuery() inside of this function

    //Alert IE6 users
//    if ($.browser.msie && $.browser.version.substr(0,1)<7) {
//
//        var IE6warning = ($.cookie("ie6-warned") === "1") ? true : false;
//
//        if(IE6warning !== true){
//            $.cookie("ie6-warned", "1", { path : "/", expires: 31 });
//            var modal = alertIE6();
//            modal.dialog({
//                modal : true,
//                title: 'Internet Explorer 6 - Old and insecure'
//            });
//        }
//    }

    //Wrap main text content in rounded corners
    $("div.column700").each( function() {
        wrapContentCorners(this);
    });

    function wrapContentCorners( ele ){
        var wrapDivs = $("<div class='top'><div class='bottom'></div></div>");
        $(ele).wrapInner(wrapDivs);

    }

    //Wrap h2s so we can set background image on Cufoned text
    $("h2").each( function() {
        wrapHeadingBackground(this)
    });
    
    function wrapHeadingBackground( ele) {
        var wrapDivs = $("<div class='header-pip'></div>");
        $(ele).wrap(wrapDivs);
    }


    //Fix IE problems
    $('img').supersleight({shim: 'http://www.sweet-apple.co.uk/wp-content/themes/sweetapple-v3/images/x.gif'});

    //Fix IE input:focus bugs
    $("input, textarea").focus(function(){
       $(this).css({ 'background-color' : '#f1f1f1'});
    });

    //Make the signup form more compact
    if($("#signup").length) {
        
        var subscribeFields = new Array("div.mc_merge_var", "div.mc_interest", "#mc-indicates-required", "#mc_interests_header");
        //Hide all fields
        for ( var i in subscribeFields ){
            $(subscribeFields[i]).hide();
        }

        var subscribeInputs = $("div.mc_merge_var");
        var emailInput = subscribeInputs[0];
        $(emailInput).show();

        $("input", emailInput).focus( function() {
            for ( var i in subscribeFields ){
                $(subscribeFields[i]).show();
            }
        });
    }

    // XHTML Strict compliance
    $("a[class=external]").each(function(){
        var oldtitle = $(this).attr("title");
		$(this).attr("title", oldtitle + " (opens in a new browser window)");
		$(this).click(function(){
			openExternalTrackedLink(this);
		});
	})

    //Have they already visited the AppleStore in last 7 days?
    var visitedAppleStore = ($.cookie("store-visited") === "1") ? true : false;
    $("a[class=applestore]").each(function(){
        var oldtitle = $(this).attr("title");
		$(this).attr("title", oldtitle + " (opens in a new browser window)");

        $(this).click(function(){

            var theLink = this;

            if(visitedAppleStore) {
                openExternalTrackedLink(this);
            }else{
                var modal = alertAppleStore();
                modal.dialog({
                    modal : true,
                    title: 'Thanks for helping',
                    buttons: {
                        "Continue": function() {
                            $(this).dialog("close");
                            visitedAppleStore = true;
                            $.cookie("store-visited", "1", { path : "/", expires: 7 });
                            openExternalTrackedLink(theLink)
                        }
                    }
                });

                
            }
            return false;
        });

	});

    function alertAppleStore() {
        var theModal = $("<div id='applestore-notify'><p>We're going to whisk you off to the AppleStore. Anything you buy there after directly visiting from my site earns me 2% commission - which is much appreciated.</p></div>");
        return theModal;
    }

    function alertIE6() {
        var theModal = $("<div id='ie6-notify'><p>Hello. You are using Internet Explorer 6, which is a very old and insecure browser. You should install a more modern browser, such as <a href='http://www.browserchoice.eu' targe='_blank'>Internet Explorer 8, Firefox, Chrome or Safari</a></p></div>");
        return theModal;
    }

    function openExternalTrackedLink(element){
        if(typeof pageTracker === 'function') {
            pageTracker._trackPageview("external/" + $(element).attr('title'));
        }
        window.open(element.href);
        return false;
    }

    //Hightlight the currently selected page and any parents
    $('li.current_page_ancestor a, li.current_page_parent a, li.current_page_item a').each(function(){        
        var bgStr = $(this).backgroundPosition();
        if(bgStr){
            bgArray = bgStr.split(" ");
            var thisHeight = ($(this).css('height') !== "auto") ? "-" + $(this).css('height') : "auto";
            bgArray[1] = thisHeight;
            $(this).setBackgroundPosition( bgArray.join(' ') );
        }
        
    });



    $("ul[class*=parent] > li").each(function(){

////      $(this).css("z-index", 30);
////        var parentWidth = $(this).width();
//
//        //Centre the child menus under the parent. Maths!
////        var childMenu = $("ul.children", this);
////        var childWidth = $(childMenu).width();
////        //var centrePoint = ( parentWidth - childWidth)/2;
//
//
//        //Not working as childMenu always exists. Understand context selectors in JQuery
////        if(childMenu) {
////            var centerPoint = 0;
////        }
//
////        $(this).hover(
////            function(){
////                $("ul.children", this).css({top : '100px'});
////            },
////            function(){
////                $("ul.children", this).css({top : '-1000px'});
////        });

        if( $.browser.msie !== true ) {
            $(this).hover(
                function(){
                   //Stop the background position being set on :hover
                   $("ul.children", this).css( { top : "-400px"} );

                   $("ul.children", this).animate({
                        opacity : 1,
                        top : '207px'},
                        { duration : 250,
                          queue : false}
                    );
                },
                function(){
                    $("ul.children", this).stop(true,false).animate({
                        opacity : 0,
                        top : '-100px'},
                        250
                    );

             });
        }else{
            $(this).hover(
                function(){
                    $("ul.children", this).css( { top : "207px"} );
                },
                function(){
                    $("ul.children", this).css( { top : "-1000px"} );
                }
            );
        }
        
    });
     Cufon.replace(['#content h1','#content h2'], {hover: true, textShadow: '1px 1px #ffffff'});

})