$(document).ready(function () {
    var pathname = window.location.pathname;
    if(pathname.match(/free.jsp/)) {
      $('#contentWrapper').append('<div id="callouts"></div>');

      //var callout = '<div id="mythic" style="padding: 10px 0"><a href="http://www.samsung.com/us/consumer/mobile/mobile-phones/at-t-phones/SGH-A897ZKAATT/index.idx?pagetype=prd_detail&returnurl"><img src="images/callouts/Mythic_Callout.jpg" alt="Mythic"/></a></div>';
      var callout = '<div id="guinness" style="padding: 10px 0pt;"><a href="http://www.samsungmobileusa.com/Promotions.aspx"><img alt="The worlds fastest texting touchscreen. Guinness World Record." src="images/callouts/guinness_Callout.jpg"></a></div>';
      $('#callouts').prepend(callout);
    }


    // ACCORDION FUNCTIONALITY THROUGH JQUERY UI
    $('#accordion').accordion({ header: 'h3',autoHeight: false });
    $('#accordion h3').hover(function () {
        if (! $(this).hasClass('ui-state-active')) {
            $(this).css({'text-decoration':'underline', 'cursor':'pointer'});
        }
    }, function () {
        $(this).css({'text-decoration':'none', 'cursor':'default'});
    });


    $('#accordion div, #related').each(function() {
        $(this).find('div.item:even').addClass('odd');  //REMEMEMBER JQUERY :EVEN IS ZERO BASED
    });


    //CAROUSEL FUNCTIONALITY DOCUMENTED HERE: http://sorgalla.com/projects/jcarousel/
    //CAROUSEL CAN BE SET TO AUTO-SCROLL, AND WRAP IF DESIRED.
    $('.jcarousel-skin').jcarousel( {
        scroll:4,
        visible:4
    });


    //STAR RATING FUNCTIONALITY DOCUMENTED HERE: http://www.fyneworks.com/jquery/star-rating/
    $('input.starRating').rating({
        callback: function(value, link){
        // 'this' is the hidden form element holding the current value
        // 'value' is the value selected
        // 'element' points to the link element that received the click.
        
        alert('You rated this product: ' + value + ' stars!');
        
        // To submit the form automatically:
        // this.form.submit();
        
        // To submit the form via ajax:
        // $(this.form).ajaxSubmit();
        }
    });


    $('div.controls ul.displayType li').click(function() {
        $('div.controls ul.displayType li').removeClass('active');

        if ($(this).hasClass('grid')) {
            $('div.controls ul.displayType li.grid').addClass('active');
            $('div.items').removeClass('list').addClass('grid');

            $('div.grid div.item').each(function() {
                $(this).children('h5').css('width','auto');
            });
        } else {
            $('div.controls ul.displayType li.list').addClass('active');
            $('div.items').removeClass('grid').addClass('list');

            $('div.list div.item').each(function() {
                var wrapperW = $(this).parent().outerWidth(true);
                var h4W = $(this).find('h4').outerWidth(true);
                var thumbW = $(this).find('p.thumb').outerWidth(true);
                var ratingW = $(this).find('p.rating').outerWidth(true);
                var priceW = $(this).find('p.price').outerWidth(true);
                var previewW = $(this).find('p.preview').outerWidth(true);
                var getItNowW = $(this).find('p.getItNow').outerWidth(true);
    
                var h5W = wrapperW - (h4W + thumbW + ratingW + priceW + previewW + getItNowW);
                $(this).find('h5').css({'margin-left':'0','margin-right':'0','padding-left':'0','padding-right':'0','width':h5W});
            });
        }
    });




    $('p.preview a').live('click', function() {
        if ($(this).hasClass('play')) {
            $(this).removeClass('play');
        } else {
            $(this).addClass('play');
        }
        return false;
    });

    
    $('#selectedProduct #product div.thumbs p img').click(function() {
        $('#selectedProduct #product div.thumbs p.main img').attr({
            src:$(this).attr('src')
        });
    });    


    $('#selectedProduct #product div.thumbs p').hover(function () {
        if (! $(this).hasClass('main')) {
            $(this).css({'cursor':'pointer'});
        }
    }, function () {
        $(this).css({'cursor':'default'});
    });


    $('form#review .comment textarea').focus(function () {
        $(this).attr('rows','4').css('height','auto');
    });

    if(typeof sIFR == "function") {
        if ($('body').hasClass('join') || $('body').hasClass('search')) {
            sIFR.replaceElement("h1.sIFR", named({sFlashSrc: "mm/headlines/helveticaNeueThin.swf", sColor: "#0a2c63", sWmode: "transparent"}));
        } else {
            sIFR.replaceElement("h1.sIFR", named({sFlashSrc: "mm/headlines/helveticaNeueThin.swf", sColor: "#ffffff", sWmode: "transparent"}));
        }
    };

    $('#selectedProduct #product div.thumbs p:nth-child(6)').addClass('noMargin');
    $('body.ringtones #content #related div.item:nth-child(5)').addClass('noMargin');

    $('body.ringtones #content div.item').hoverIntent(function() {
        
        var productId = $(this).attr('name'); 
        
        if ( $(this).parent('div').hasClass('grid') ) {
            $(this).append('<div class="hover"><p class="close"><a href="#">Close</a></p><div class="content"></div><div>');

            var content = $(this).find('div.content');

            $(this).children('h5').clone().appendTo(content);
            $(this).children('p.price').clone().appendTo(content).show();
            $(this).children('p.preview').clone().appendTo(content).show();
            content.append('<p class="getItNow"><a>Get It Now!</a></p>');

            $(this).children('div').show();

            var getItNowBtn = $(content).find('p.getItNow');

            $(getItNowBtn).click(function(e) {
                showCarrierBillingPopup(e, productId);
            });
        }
    }, function() {
        $(this).children('div').remove();
    });

    
    $('p.getItNow').click(function(e) {
        var productId = $(this).parent().attr('name');
         
        if ($('#deviceSelectedId').val() == "") {
        	$(this).find('a').removeAttr('href');
        	
            showDeviceSelectorPopup(e, productId);
        } else if($(this).parent().hasClass("cb")) {
        	$(this).find('a').removeAttr('href');
        	
            showCarrierBillingPopup(e, productId);
        }
    });
    
    function showDeviceSelectorPopup(e, productId) {
    	e.stopPropagation(); // Stops the following click function from being executed
    	
    	$(this).parent('div').hide();
        var windowWidth = document.documentElement.clientWidth;
        var windowHeight = document.documentElement.clientHeight;
        var popupHeight = $("#devicePopup").height();
        var popupWidth = $("#devicePopup").width();

        $("#devicePopup").css({
             "position": "absolute",
             "top": e.pageY - 200,
             "left": windowWidth/2-popupWidth/2
        });

        $("#popHeader h2").html("You must select a device to continue.");
        $("#devicePopup").fadeIn("slow");
        
        var deviceCompatSuccessUrl = $("#leftNavSuccessUrl").val();
        if (deviceCompatSuccessUrl.indexOf('?') >= 0)
        {
        
        $("#leftNavSuccessUrl").val(deviceCompatSuccessUrl + "&deviceCompat=" + productId);
        }

		else
		{
			$("#leftNavSuccessUrl").val(deviceCompatSuccessUrl + "?deviceCompat=" + productId);
		}
    }

    /**
     *
     *
     * @param productId
     */
    function showCarrierBillingPopup(e, productId) {
    	e.stopPropagation(); // Stops the following click function from being executed
    	
        // WORKAROUND to flash player z-index not working on Firefox and Linux.
        if($.browser.linux() && $.browser.firefox())
            $('p.preview').hide();

        var carrierBillingPopup = $('#carrierBillingPopup');
        var height = $(carrierBillingPopup).height();
        var width = $(carrierBillingPopup).width();
        
        $('#cartItems').hide();
        $('#carrierBillingPopupMessage').hide();
        $('#carrierBillingPopupMessageContainer').hide();
        $('#carrierBillingPopupContainer').show();
        

        var addToCartForm = $('#cart' + productId);
        var addToCartClone = addToCartForm.clone();

        // add the selected item to the cart and forward to carrier_billing_cart_items.jsp
        $(addToCartClone).attr('action', 'carrier_billing_cart_items.jsp?_DARGS=/Synchronicity/HTML/includes/add2cart_common.jsp&currency=USD&sf=59990044pg');
        $(addToCartClone).find('input[name=/motricity/commerce/order/ShoppingCartModifier.addItemToOrderSuccessURL]').val('carrier_billing_cart_items.jsp');

        var options = { 
            target: '#cartItems', 
            success: function() {
                $('#cartItemsLoading').hide();
                $('#cartItems').show();
            }
        };

        $(addToCartClone).submit(function() {
          $('#cartItemsLoading').show();
          $(this).ajaxSubmit(options);

          return false;
        });
        $(addToCartClone).submit();

//          var cartUpdateOptions = { target: '#carrierBillingPopup' };
        var couponForm = $('#cartUpdate');

        $(couponForm).submit(function() {
          $(this).ajaxSubmit(options);

          return false;
        });

        var phoneNumForm = $('#phoneNum');
        var productIdField = phoneNumForm.find('input[name=productId]');
        productIdField.val(productId);

        // Sets up asynchronous form submission for phone number
        var phoneNumFormOptions = { 
            target: '#carrierBillingPopupMessage',
            success: function() {
                $('#carrierBillingPopupMessageLoading').hide();
                $('#carrierBillingPopupMessage').show();
            }
        };
        
        $(phoneNumForm).unbind('submit');
        $(phoneNumForm).submit(function() {
            $('#carrierBillingPopupContainer').hide();
            $('#carrierBillingPopupMessageLoading').show();
            $('#carrierBillingPopupMessageContainer').show();
            
            $(this).ajaxSubmit(phoneNumFormOptions);
            
            return false;
        });

        // Positioning of the popup
        $(carrierBillingPopup).css({
            left: e.pageX-(width/2)+"px",
            top: e.pageY-(height/2)+"px"
        }).show();

        // Close button for popup
        var closeBtn = $(carrierBillingPopup).find('p.close');
        $(closeBtn).one("click", function(f) {
            $(carrierBillingPopup).hide();
            $('#cartItems').hide();

            // WORKAROUND to flash player z-index not working on Firefox and Linux.
            if($.browser.linux() && $.browser.firefox())
                $('p.preview').show();
        });
    }


/*
********************************************************************************
    JOIN PAGE TABS
********************************************************************************
*/    


    $('#content div.tabs ul li').click(function() {
        $('#content div.tabs form div').hide();
        $('#content div.tabs form div.' + $(this).attr('class') + ', #content div.tabs form div.' + $(this).attr('class') + ' div.pref').show();
        $(this).parent().removeClass().addClass($(this).attr('class'));
    });
    
    if($.browser.msie) {
        $('body.join #content div.tabs').css('zoom',1);
    }



/*
********************************************************************************
    SEARCH PAGE
********************************************************************************
*/    

    if(($.browser.msie) && $('body').hasClass('search')) {
        $('div#searchResults').css('zoom',1);
    }


    if($('body').hasClass('search')) {
        $('div#searchResults div.item').each(function() {
            var wrapperW = $(this).parent().outerWidth(true);
            var h4W = $(this).find('h4').outerWidth(true);
            var thumbW = $(this).find('p.thumb').outerWidth(true);
            var ratingW = $(this).find('p.rating').outerWidth(true);
            var priceW = $(this).find('p.price').outerWidth(true);
            var previewW = $(this).find('p.preview').outerWidth(true);
            var getItNowW = $(this).find('p.getItNow').outerWidth(true);

            var h5W = wrapperW - (h4W + thumbW + ratingW + priceW + previewW + getItNowW);
            $(this).find('h5').css({'margin-left':'0','margin-right':'0','padding-left':'0','padding-right':'0','width':h5W});
        });
    }

    
/*
********************************************************************************
    IE6 CODE
********************************************************************************
*/    
    if (isIE6) {
        $('#content div.ringtones h4+ul+div.item, #content div.ringtones p:first-child, #feature #sub ul li:first-child,#content #reviews form+div.review, form#review .comment ul li:first-child, #selectedProduct #product div.thumbs p.main+p, body.ringtones #content div.ringtones div.pagination+div.item, ul.all li:first-child, body.myPicks #content div.ringtones h4+div.item').addClass('first-child');
        $('body.ringtones #content #related h3+div.item').addClass('noMargin');

        $('#content .controls ul.displayType li').hover(function () {
            $(this).addClass('active')
        }, function () {
            $(this).removeClass('active')
        });
        
        

        
        
        
    }
});
