/** -------------------------
 * commentTab.js
 * used on content detail leave a comment / send to friend page
 * to control tabbed browsing, form submission, error checking
 * @author: julia yu
 */

var Juniper = window.Juniper || {};

Juniper.commentTab = {

    // globals
    limit: {
        friendCount: 5,
        phoneCount: 100
    },
    selected: (location.href.indexOf('send-to-friend') !== -1) ? 'share' : (location.href.indexOf('reviews') !== -1) ? 'comment' : 'related',

    // initialize global variables
    friendCount: 0,
    phoneCount: 0,

    /* remove nodes with the error class
        @input: item - DOM element scope of error
    */
    removeError: function(item) {
        myScope = item;
        $(myScope).each(function(i, n){
            if ($(n).is(".flag")) {
                $(n).remove();
            }
        })
    },

    /* add a flag node with error text
        @input: item - DOM element scope of error
        @input: errorText - string error
    */
    addError: function(item, errorText) {
        myScope = item;
        $('p.flag', myScope).remove();
        myScope.prepend('<p class="flag">'+ errorText + '</p>');
    },

    /* check the phone number validity via ajax
        add to a list of phone numbers if valid, otherwise, display errors
        @input: e - click event on add phone
    */
    checkPhone: function(scope, textField, list){
        var myNumber = $(textField).val();
        var phoneCheckUrl = "/content/"+Juniper.contentItem.id +"/send/validate-phone";

        $.post(phoneCheckUrl, {phoneNumber: myNumber},
            function(data){
                if(data.success){
                    Juniper.commentTab.removeError($(textField).siblings());
                    Juniper.commentTab.addToList("phoneCount", list, myNumber, myNumber, data.removeText, data.errorMessageText);
                    Juniper.commentTab.phoneCount++;
                } else {
                    Juniper.commentTab.removeError($(textField).siblings());
                    $.each(data.errors, function(i, n){
                        Juniper.commentTab.addError($(textField).parent(), n);
                    });
                }
            },
        "json");
    },

    /* tally all the information in a list based on REL
        @input: scope - DOM element scope of list
    */
    tally: function(scope){
        var total = "";
        $("ul li a",scope).each(function(i, n){
            total = total + $(n).attr("rel") + ",";
        })
        if (total) {
            total = total.replace(/.$/,'');
        }
        return total;
    },

    /* append dynamic info to form and sent it, clear old info when sent
        @input: e - click event on submit
    */
    submitShareForm: function(e){
        if(e && e.preventDefault) { e.preventDefault(); }

        var myForm = $(this).parents("form");
        var numbers = Juniper.commentTab.tally($(".phoneNumberSet", myForm));
        myForm.append('<input type="hidden" name="phoneNumberArray" id="phoneNumbers" value="'+ numbers +'" />');
        var friends = Juniper.commentTab.tally($(".friendSet", myForm));
        myForm.append('<input type="hidden" name="friendsArray" id="myFriends" value="'+ friends +'" />');
        var that = this;

        Juniper.commentTab.submitForm(myForm, that, function(){
            $(".phoneNumberSet ul").empty();
            $(".friendSet ul").empty();
            $("#phoneNumbers").remove();
            $("#myFriends").remove();
        }, false)
    },

    /* send the comment form and clear old fields after sending
        @input: e - click event on submit
    */
    submitCommentForm: function(e) {
        if(e && e.preventDefault) { e.preventDefault(); }
        var myForm = $(this).parents("form");
        var that = this;

        Juniper.commentTab.submitForm(myForm, that, function(){
            $("#commentTitle").val("");
            $("#comment").val("");
        }, true)
    },

    /* submit the form via ajax and show the thank you tabs
        @input: myForm - DOM form
        @input: scope - DOM scope of form errors
        @input: callback - function to execute after submit
    */
    submitForm: function(myForm, scope, callback, isReview){
        $.ajax({
                type: "POST",
                url: $(myForm).attr("action"),
                data: $(myForm).serialize(),
                dataType: "json",
                success: function(response){
                    if (response.success) {
                        if(Juniper.commentTab.selected == 'comment') {
                            var hash = location.hash;
                            if (isReview && hash == '#reviewComment') {
                                hash = "/content/"+Juniper.contentItem.id +"/reviews";
                            }
                            hash = hash.replace(/^#/, '')+'?fragment=1';
                            Juniper.content.replaceContent(hash);
                            self.scrollTo(0,0);
                        } else {
                            $(scope).parents(".tabContent").hide();
                            $(scope).parents(".tabContent").siblings(".thanksTabContent").show();
                        }

                        // for tracking purposes
                        Juniper.commentTab.submitTracking();
                    } else {
                        $(response.errors).each(function(i, n){
                            if (isReview) {
                                Juniper.commentTab.addError($(scope).parents(".tabContent .reviewContent form"), n);
                            } else {
                                Juniper.commentTab.addError($(scope).parents(".tabContent"), n);
                            }

                        });
                        callback();
                    }
                }
            });
    },

    // Omniture tracking only
    submitTracking: function() {
        var pageName = s.pageName.substr(0,s.pageName.lastIndexOf(':')+1);

        switch ( Juniper.commentTab.selected ) {
            case 'share':
                s.events='event26';
                s.prop32 = 'fw:content shared';
                s.pageName = pageName + 'shared';
                s.t();
                break;
            case 'comment':
                s.events='event34';
                s.prop32 = 'fw:content commented';
                s.pageName = pageName + 'commented';
                s.t();
                break;
                }
    },

    /* 	append some item to a list with option to remove
        exit if the item already exist in list, or has reached count limit
        @input: type - string limit type
        @input: list - DOM scope of item list
        @input: item - string new item to be added to list
        @input: info - string REL value of item
    */
    addToList: function(type, list, item, info, removeText, errorMessageText){
        var fail = false;

        $("li", list).each(function(i, n) {
            var existingValue = $("span", n).text();
            if (existingValue == item) {
                fail = true;
            }
        });

        if (Juniper.commentTab[type] >= Juniper.commentTab.limit[type]) {
            Juniper.commentTab.addError($(list.parents("fieldset")), errorMessageText);
            fail = true;
        }

        if (fail) {
            return;
        }

        $(list).append('<li style="display: none"><span>' + item + '</span> <a href="#" rel="' + info + '">' + removeText + '</a></li>');
        $("li:last", list).fadeIn(1000);
        $("li:last a", list).live("click", function(e){
            e.preventDefault();
            $(this).parent().remove();
            Juniper.commentTab[type]--;
        });
    },

    /* add the selected friend to our list
        @input: e - click event on add friend
    */
    showFriend: function(select, list){
        //if(e && e.preventDefault) e.preventDefault();

        var myFriends = $("option:selected", select);
        var friendIndex = $(myFriends).attr("value");
        var friendName = $(myFriends).text();

        Juniper.commentTab.addToList("friendCount", list, friendName, friendIndex);
        Juniper.commentTab.friendCount++;
    },

    setupAddFriend: function(e){
        if(e && e.preventDefault) { e.preventDefault(); }

        var select = $("#friendList");
        var list = $(".friendSet ul");

        Juniper.commentTab.showFriend(select, list);
    },

    setupAddPhone: function(e){
        if(e && e.preventDefault) { e.preventDefault(); }

        var scope = $(".phoneNumberSet");
        var textField = $("input.text", scope);
        var list = $("ul", scope);

        Juniper.commentTab.checkPhone(scope, textField, list);
    },

    /* set up tab toggling and other events on page
    */
    init: function(){
        $("#addPhone").live("click", Juniper.commentTab.setupAddPhone);
        $("#addFriend").live("click", Juniper.commentTab.setupAddFriend);
        $("#sendShare").live("click", Juniper.commentTab.submitShareForm);
        $("#sendComment").live("click", Juniper.commentTab.submitCommentForm);
    }
}

/** -------------------------
    page load initialize
*/
$(document).ready(function(){
    Juniper.commentTab.init();
});
var Juniper = window.Juniper || {};

Juniper.content = {
    currentUri: null,

	pageload: function(hash) {
		// hash should not contain the first # character.
		if(hash && hash.indexOf('/') !== -1 && Juniper.content.currentUri !== hash) {
            // session timeout issue check for send to friend
            if (!Juniper.global.loggedInUser && hash.indexOf('send-to-friend') !== -1) {
                window.location.replace('/login');
            } else {
                // restore ajax loaded state
                Juniper.content.replaceContent(hash);
            }
		}
	},
    
    stripBaseURL: function(uri) {
        uri = uri.replace(Juniper.global.baseURL, '');
        return uri;
    },
	
    linkHandler: function(e) {
        e.preventDefault();

        var hash = this.href;
        hash = Juniper.content.stripBaseURL(hash).replace(/^.*#/, '');
        $.history.load(hash);
        //Juniper.content.replaceContent(this.href);
    },
    
    getFragment: function(uri) {
        Juniper.content.currentUri = uri;
        if( uri.indexOf('?') !== -1 ) {
            if ( uri.indexOf('fragment') === -1 ) {
                uri += '&fragment=1';
            }
        } else {
            uri += '?fragment=1';
        }
        return uri;
    },
    
    replaceContent: function(uri) {
        var $content = $('#dynamicContent');
        var contentWidth = $content.width();
        var contentHeight = $content.height();

        $content.append('<div id="overlay" />').append('<div id="loading"><img src="' + Juniper.global.staticUrl + '/com/img/preloader.gif" alt="loading..." /></div>');
        $('#overlay',$content).css({width: (contentWidth + 42), height: contentHeight, opacity: '0.6'});

        $content.load( Juniper.content.getFragment(uri), function() {
            if (Juniper.subNav && typeof Juniper.subNav.init === 'function') { Juniper.subNav.init(); }
            if (Juniper.view && typeof Juniper.view.init === 'function') { Juniper.view.init(); }
            if (Juniper.gridTip && typeof Juniper.gridTip.init === 'function') { Juniper.gridTip.init(); }
            if (Juniper.rating && typeof Juniper.rating.init === 'function') { Juniper.rating.init(); }
            if (Juniper.crumbs && typeof Juniper.crumbs.init === 'function') { Juniper.crumbs.init(); }
        });
    },
    
    init: function() {
        $("a[rel='ajax']", '#dynamicContent').live('click', Juniper.content.linkHandler);
    }
};

$(document).ready(function() {
    $.history.init(Juniper.content.pageload);
	Juniper.content.init();
});
/** ------------------------- 
 * device_select.js
 * show filterable list of devices
 * @author: julia yu 
 */

var Juniper = window.Juniper || {};

Juniper.deviceSelect = {
	// initialize globals
	showing: false,
	panel : null,
	list: null,
    terminalId: null,
    tidSet: null,
    page: null,
    
	/* reset the device selector to non selected state
	*/
    resetSelected: function() {
        $("li", Juniper.deviceSelect.list).removeClass("selectedDevice");
        Juniper.deviceSelect.terminalId = '';
    },

	/* display the device selector, hide register popup if its there
		@input: e - click event 
	*/
	showPanel: function(e) {
        if(e && e.preventDefault) { e.preventDefault(); }

		if ( !Juniper.deviceSelect.showing ) {
    		if ( Juniper.register && Juniper.register.showing ) {
        		Juniper.register.panel.fadeOut(500, function() {
            		Juniper.register.showing = false;
                });
    		} 
			Juniper.deviceSelect.panel.fadeIn(500, function() {
    			Juniper.deviceSelect.showing = true;
            });
            Juniper.deviceSelect.resetSelected();
        }

        //tracking
        s.pageName = "ovi:store:fw:device selector";
        s.products = '';
        s.events = '';
        s.t();
	},
	
	/* hide the device selector
		@input: e - click event 
	*/
    hidePanel: function(e) {
        if(e && e.preventDefault) { e.preventDefault(); }

    	if (Juniper.deviceSelect.showing) {
    		Juniper.deviceSelect.panel.fadeOut(500, function() {
        		Juniper.deviceSelect.showing = false;
            });
    	}
    },
	
	/* filter devices via class name
	*/
	filter: function() {
		var filter= $(this).parent().attr("class");
		if (filter == "allPhones") {
			$("li",Juniper.deviceSelect.list).show();
		} else {
			$("li",Juniper.deviceSelect.list).hide();
			$("li."+filter,Juniper.deviceSelect.list).show();
		}
	},
	
	/* highlight selected device and remember its ID
		@input: e - click event on device
	*/
	selectItem: function(e) {
		if(e && e.preventDefault) { e.preventDefault(); }

        Juniper.deviceSelect.terminalId = $(this).attr('rel');
		$("li", Juniper.deviceSelect.list).removeClass("selectedDevice");
		$(this).parent().addClass("selectedDevice");
	},
	
    
    setDevice: function(e) {
        if(e && e.preventDefault) { e.preventDefault(); }

        if ( !Juniper.global.deviceIsSelected ){
    		$.post('/index/flash-carousel', {deviceIsSelected: 1}, 
                function(data) {
        			if (data.success) {
                        Juniper.deviceSelect.submitDevice();
        			}
        		}, 
            "json");
        } else {
            Juniper.deviceSelect.submitDevice();
        }
    },

	/* set the phone via flash, show registeration if necessary
		@input: e - click event on submit
	*/
	submitDevice: function() {
		if ( Juniper.deviceSelect.terminalId ) {
            if( document.getElementById('nokiaSpotlight') ) {
                var swf = document.getElementById('nokiaSpotlight');
                swf.setPhone( Juniper.deviceSelect.terminalId );
            }

            Juniper.deviceSelect.sendTerminalId(function(){
                Juniper.deviceSelect.tidSet = true;

                if ( !Juniper.global.loggedInUser && Juniper.deviceSelect.page === 'home' ) {
                    if ( Juniper.register && Juniper.register.showPanel ) {
                        Juniper.register.showPanel();
                    }
                } else {
                    Juniper.deviceSelect.hidePanel();
                }
            });
        }
	},

	/* show device selector on flash click
		@input: e - click event on device
	*/
	changePhone: function(e) {
       if(e && e.preventDefault) { e.preventDefault(); }

        Juniper.deviceSelect.page = (this.rel) ? this.rel : '';

		if ( Juniper.register && Juniper.register.showing ) {
    		Juniper.register.showing = false;
    		Juniper.register.panel.fadeOut(500, Juniper.deviceSelect.showPanel);
		} else {
		    Juniper.deviceSelect.showPanel(e);
        }
	},

	/* 
	*/
    sendTerminalId: function(callback) {
        var id = Juniper.deviceSelect.terminalId;
        var page = Juniper.deviceSelect.page;

        switch ( page ) {
            case 'account':
                $.get('/account/settings/set-device', { terminalId: id, fragment: 1 }, 
                    function(data){
                        $('#selectedPhone').html(data);
                    });
                break;
            case 'detail':
                $.post(document.URL, { terminalId: id },
                    function() {
                        window.location = document.URL;
                    });
                break;
            default:
                if(Juniper.content) {
                    Juniper.content.replaceContent('/index?terminalId=' + id);
                }
        }

        if (callback !== null && typeof callback === 'function') {
            callback();
        }
    },
	
	/* set up device select panel and related events
	*/
	init: function() {
		Juniper.deviceSelect.panel = $("#deviceOverlay");
		Juniper.deviceSelect.list = $("#deviceList");
		
		$(".closer", Juniper.deviceSelect.panel).bind("click", Juniper.deviceSelect.hidePanel);
		$(".phoneCategory label input").bind("click", Juniper.deviceSelect.filter);
		$("li a", Juniper.deviceSelect.list).bind("click", Juniper.deviceSelect.selectItem);
		$("#submitDevice", Juniper.deviceSelect.panel).bind("click", Juniper.deviceSelect.setDevice);
		$("#changePhone").bind("click", Juniper.deviceSelect.changePhone);
	}
}

/** ------------------------- 
	page load initialize
*/
$(document).ready(function() {
	Juniper.deviceSelect.init();
});/** ------------------------- 
 * grid_tip.js
 * show tool tip on grid
 * @author: julia yu 
 */

var Juniper = window.Juniper || {};

Juniper.gridTip = {
	
	//global
	hideDelay: 1000,
	
	//initialize globals
	panel: null,
	showing: false,
    	onTip: false,
	timeout: null,

	showPanel: function(){
		if (!Juniper.gridTip.showing) {
			Juniper.gridTip.panel.show();
            Juniper.gridTip.showing = true;
		}
	},
	
	hidePanel: function(){
		if (Juniper.gridTip.showing) {
			Juniper.gridTip.panel.hide();
			Juniper.gridTip.showing = false;
            Juniper.gridTip.onTip = false;
		}
	},
	
	isListView: function() {
		if ($(".listView").length) {
			return true;
		} else {
			return false;
		}
	},
    
    trimSummary: function(obj) {
        var maxlength = 120;
        var delim = '&hellip;';
		var str = $(".summary",obj).text();

        if(str.length > maxlength){
            var regex = new RegExp('(.{'+maxlength+'}.*?)\\b');
            var matches = str.match(regex);
            trimmedStr = matches[0] + delim;
            return trimmedStr;
        } else {
            return str;
        }
    },
	
	/* 	clone the entity in the grid view 
		reduce summary length to fit
		@input: entity - DOM grid entity
	*/
	populateTip: function(entity){
        var summary = Juniper.gridTip.trimSummary(entity);

		$('.entityActions', Juniper.gridTip.panel)
			.empty()
			.append($('.entityActions li:not(.price, .downloaded)', entity).clone())
			.append($('.entityActions li.price', entity).clone())
			.append($('.entityActions li.downloaded', entity).clone());

		$('.tipContent', Juniper.gridTip.panel)
			.empty()
			.append($('.entityTitle', entity).clone())
			.append($('.beforeRating', entity).clone())
			.append($('h5', entity).clone())
			.append('<p class="summary">'+ summary +'</p>');
	},

	/* 	position the tool tip
		@input: thumbPosition - JQuery pos object
	*/
	positionTip: function(thumb){

        var containerWidth = thumb.parents('.sectionContent').width();
        var tipWidth = parseInt(Juniper.gridTip.panel.width() + 40); //tip width + padding
        var thumbWidth = thumb.width();
        var tipYOffset = 20;
        var tipXOffset = thumbWidth;
        
	// adding and removing to reload the shadow in ie
        if(Juniper.gridTip.panel.hasClass('tipLeft')){
            Juniper.gridTip.panel.removeClass('tipLeft');
            Juniper.gridTip.panel.addClass('tipLeft');
        } 
	 else {
            Juniper.gridTip.panel.addClass('tipLeft');
            Juniper.gridTip.panel.removeClass('tipLeft');
	}

        var thumbPosition = thumb.position();
	var tipY = thumbPosition.top - tipYOffset;
	var tipX = thumbPosition.left + tipXOffset;
		
        // check that the tip isn't going out of bounds
	if ((tipX + tipWidth) > containerWidth) {
         	tipXOffset = tipWidth;
            	Juniper.gridTip.panel.removeClass('tipLeft');
            	Juniper.gridTip.panel.addClass('tipLeft');
		tipX = thumbPosition.left - tipXOffset;
	} else {
            	Juniper.gridTip.panel.addClass('tipLeft');
            	Juniper.gridTip.panel.removeClass('tipLeft');
	}

	Juniper.gridTip.panel.css({
            'top': tipY,
            'left': tipX
        });
	},
	
	onOver: function(){
		if (Juniper.gridTip.isListView()) {
			return;
		}
		
		clearTimeout(Juniper.gridTip.timeout);
        Juniper.gridTip.onTip = false;
		Juniper.gridTip.populateTip($(this).parent());
		Juniper.gridTip.positionTip($(this).parent('li'));
		Juniper.gridTip.showPanel();
	},
	
	onOut: function(){
		if (Juniper.gridTip.showing && !Juniper.gridTip.onTip) {
            Juniper.gridTip.timeout = setTimeout("Juniper.gridTip.hidePanel()", 500);
        }
	},
	
	onPanelOver: function() {
		if (Juniper.gridTip.isListView()) {
			return;
		}
        Juniper.gridTip.onTip = true;
		clearTimeout(Juniper.gridTip.timeout);
	},
	
	onPanelOut: function() {
        Juniper.gridTip.timeout = setTimeout("Juniper.gridTip.hidePanel()", Juniper.gridTip.hideDelay);
	},
	
	init: function(){
		$("#gridViewContainer").append('<div id="hoverPanel"></div>');
		Juniper.gridTip.panel = $("#hoverPanel");
		Juniper.gridTip.panel.append('<div class="tipContent"/>'
                                    +'<ul class="entityActions actionsSm"/>'
                                    +'<div class="tip-top-left"/>'
                                    +'<div class="tip-top-right"/>'
                                    +'<div class="tip-bottom-left"/>'
                                    +'<div class="tip-bottom-right"/>'
                                    +'<div class="tip-v"/>'
                                    +'<div class="tip-h"/>'
                                    +'<div class="tip-pointer"/>');

		var thumbNails = $(".entity .thumb");
		thumbNails.hoverIntent(
            Juniper.gridTip.onOver,
            Juniper.gridTip.onOut
        );
		
		Juniper.gridTip.panel.hover(
            Juniper.gridTip.onPanelOver,
            Juniper.gridTip.onPanelOut
        );
	}
}

/** ------------------------- 
	page load initialize
*/
$(document).ready(function(){
	Juniper.gridTip.init();
});
/** ------------------------- 
 * mystuff_hover.js
 * show updates on my stuff in popup
 * @author: julia yu 
 */

var Juniper = window.Juniper || {};

Juniper.mystuffHover = {
	shown: false,
	showing: false,
	panel: null,
	button: null,
	
	showStatus: function(e){
		if(e && e.preventDefault) { e.preventDefault(); }
		
		if (!Juniper.mystuffHover.showing && !Juniper.mystuffHover.shown) {
			Juniper.mystuffHover.shown = true; // first shown
			Juniper.mystuffHover.panel.fadeIn(500, function() {
    			Juniper.mystuffHover.showing = true;
            });
		}
	},
	
	hideStatus: function(e){
		if(e && e.preventDefault) { e.preventDefault(); }
		
		if (Juniper.mystuffHover.showing) {
			Juniper.mystuffHover.panel.fadeOut(500, function() {
    			Juniper.mystuffHover.showing = false;
                Juniper.mystuffHover.button.removeClass("hasUpdate");
            });
		}
	},
	
	init: function(){
		Juniper.mystuffHover.panel = $("#myStuffOverlay");
		Juniper.mystuffHover.button = $("#homeNavMystuff");
		$(".closer", Juniper.mystuffHover.panel).bind("click", Juniper.mystuffHover.hideStatus);
		if (Juniper.mystuffHover.button.hasClass("hasUpdate")) {
			Juniper.mystuffHover.button.bind("mouseover", Juniper.mystuffHover.showStatus);
		}
		
	}	
}

/** ------------------------- 
	page load initialize
*/
$(document).ready(function(){
	Juniper.mystuffHover.init();
});
	/** ------------------------- 
 * rateMe.js
 * process star rating
 * @author: julia yu 
 */

var Juniper = window.Juniper || {};

Juniper.rating = {

	/*  a rating has been selected
		@input: e - mouse click event
	*/
	onRated: function(e) {
		if(e && e.preventDefault) { e.preventDefault(); }
		
		var currentStar = $("a", this).attr("rel");
		var myGroup = $(this).parents("ul.stars");
		Juniper.rating.resetRating(myGroup); 
		$("li",myGroup).slice(0, currentStar).addClass("on");
		$(".rating", myGroup).text(currentStar);
		Juniper.rating.update(currentStar, myGroup, $(".contentID", myGroup).text());
	},
	
	/*  a rating has been hovered over
		@input: e - mouse in event
	*/
	onOver: function(e) {
		var myGroup = $(this).parents("ul");
		var currentStar = $("a", this).attr("rel");
		Juniper.rating.resetRating(myGroup); 
		$("li",myGroup).slice(0, currentStar).addClass("over");
	},
	
	/*  a rating has been hovered out
		@input: e - mouse out event
	*/
	onOut: function(e) {
		var myGroup = $(this).parents("ul");
		Juniper.rating.resetRating(myGroup);
		var defaultRating = $(".rating", myGroup).text();
		Juniper.rating.setRating(myGroup, defaultRating); 
	},

	/*  set the rating and show the appropriate response
		@input: rating - int rating index
		@input: myGroup - DOM scope
		@input: contentID - string item rated
	*/
	update: function(rating, myGroup, contentID) {
		/*
		 myGroup.attr("style", "background: none");
		 $(".star", myGroup).hide();
		 $(".thankYou", myGroup).show();
		 */

		contentID = $.trim(contentID); //whitespace issue with IE
		var postURL = Juniper.global.baseURL + '/content/'+ contentID +'/rate';
		$.post(postURL, 
			{rating: rating, token: Juniper.global.token, format: 'json'},
			function(data) {
				if(data.success) {
					myGroup.css("background", "none");
					$(".star", myGroup).hide();
					$(".thankYou", myGroup).show();
				} else {
					$(".thankYou", myGroup).hide();
					$(".star", myGroup).show();
				}
			}, 
		"json");
	},

	/* set all stars to the off position based on the UL group
		@input: myGroup - DOM scope of star set
	*/
	resetRating: function(myGroup) {
		$("li",myGroup).removeClass("on");
		$("li",myGroup).removeClass("over");
	},
	
	/* set the current rating 
		@input: myGroup - DOM scope
		@input: myRating - int rating index
	*/
	setRating: function(myGroup, myRating) {
		$("li", myGroup).slice(0, myRating).addClass("on");
	},
	
	/* set up every star with events
		@input: item - DOM star
	*/
	bindStarActions: function(item) {
		item.bind("click", Juniper.rating.onRated);
		item.bind("mouseover", Juniper.rating.onOver);
		item.bind("mouseout", Juniper.rating.onOut);
	},
	
	/* set up star sets
	*/
	init: function(){
        if(Juniper.global.loggedInUser) {
    		$("ul.stars li.star").each(function(i, star) {
    			Juniper.rating.bindStarActions($(star));
    		});
        } else {
            $("ul.stars li.star").live('click', function() {
                return false;
            });
        }
	}
}

/** ------------------------- 
	page load initialize
*/
$(document).ready(function(){
    Juniper.rating.init();
});
/** ------------------------- 
 * register.js
 * registration flow on home page
 * @author: julia yu 
 */

var Juniper = window.Juniper || {};

Juniper.register = {
	showing: false,
	panel : null,
	
	showPanel: function(e) {
        if(e && e.preventDefault) { e.preventDefault(); }

		if (!Juniper.register.showing) {
            var queryStr = '';
            if (Juniper.deviceSelect && !Juniper.deviceSelect.tidSet && Juniper.deviceSelect.terminalId ) {
                queryStr = 'fragment=1&terminalid=' + Juniper.deviceSelect.terminalId;
            } else {
                queryStr = 'fragment=1';
            }

    		if (Juniper.deviceSelect && Juniper.deviceSelect.showing) {
        		Juniper.deviceSelect.panel.fadeOut(500, function() {
             		Juniper.deviceSelect.showing = false;
                    Juniper.register.loadForm(queryStr);
                });
    		} else {
                Juniper.register.loadForm(queryStr);
    		}
        }
	},
	
    hidePanel: function(e) {
        if(e && e.preventDefault) { e.preventDefault(); }

    	if (Juniper.register.showing) {
    		Juniper.register.panel.fadeOut(500, function() {
                Juniper.register.showing = false;
            });
    	}
    },
    
    loadForm: function(queryStr) {
        $('#registerContent').load('/register?' + queryStr, function() {
			Juniper.register.panel.fadeIn(500, function() {
    			Juniper.register.showing = true;
            });
        });
    },

	submitForm: function(e) {
		if(e && e.preventDefault) { e.preventDefault(); }
        
        var regForm = $('#registrationForm');

        $.post(regForm.attr('action'), regForm.serialize(),
            function(data) {
                if( data.indexOf('id="success"') !== -1 ) {
                    window.location = '/';
                } else {
                    $('#registerContent').html(data);
                }
            },
        "html");
	},
	
	changePhone: function(e) {
		if(e && e.preventDefault) { e.preventDefault(); }

		if (Juniper.deviceSelect) {
        	if (Juniper.register.showing) {
        		Juniper.register.showing = false;
        		Juniper.register.panel.fadeOut(500, Juniper.deviceSelect.showPanel);
        	}
		}
	},
	
	init: function() {
		Juniper.register.panel = $("#registerOverlay");
		$(".closer", Juniper.register.panel).bind("click", Juniper.register.hidePanel);
		$("#registerLater", Juniper.register.panel).live("click", Juniper.register.hidePanel);
		$("#accept", Juniper.register.panel).live("click", Juniper.register.submitForm);
		$("#changePhone", Juniper.register.panel).live("click", Juniper.register.changePhone);
		
		$("#testregister").bind("click", Juniper.register.showPanel);
	}
}

/** ------------------------- 
	page load initialize
*/
$(document).ready(function() {
	Juniper.register.init();
});/** -------------------------
 * sendtophone.js
 * show pop up when send to phone is clicked
 * @author: julia yu
 */

var Juniper = window.Juniper || {};

Juniper.sendToPhone = {
	showing: false,
	panel : null,
	currentItem: null,
    DCCID: null,
    instructionMessage: null,
    sendingMessage: null,
    sentMessage: null,
    submitButton: null,

	/*	revert panel state to normal
	*/
    resetPanel: function() {
        ;;; console.log("Juniper.sendToPhone.resetPanel()");
        if($('#currentMobile').length > 0) {
            $('#currentMobile').show();
            $('#changePhoneField').hide();
        }
        $('#newMobileNumber').val('+');

        Juniper.sendToPhone.instructionMessage.show();
        Juniper.sendToPhone.sendingMessage.hide();
        Juniper.sendToPhone.sentMessage.hide();
        Juniper.sendToPhone.formContainer.show();

        $('li.error', Juniper.sendToPhone.panel).remove();
    },

	/*	show the panel relative to the button pushed
		@input: e - send to phone click event
	*/
	showUpdate: function(e) {
        ;;; console.log("Juniper.sendToPhone.showUpdate()");
		if(e && e.preventDefault) { e.preventDefault(); }

		if ($(this).hasClass("disableButton")) {
			return false;
		}

        Juniper.sendToPhone.resetPanel();
		Juniper.sendToPhone.currentItem = this.rel.split(':')[0];
		Juniper.sendToPhone.DCCID = this.rel.split(':')[1];

		if (!Juniper.sendToPhone.showing) {
			Juniper.sendToPhone.showing = true;
			Juniper.sendToPhone.panel.fadeIn(300);
		}

		// move the panel to the right place
		var buttonPosition = $(this).offset();

		var newLeft = buttonPosition.left - 400;
		if (newLeft < 0) {
			newLeft = 0;
		}

		Juniper.sendToPhone.panel
			.css({
                "left": newLeft,
                "top": buttonPosition.top - 100
            });

	},

	/* 	hide panel
		@input: e - submit click event
	*/
	hideStatus: function(e) {
        ;;; console.log("Juniper.sendToPhone.hideStatus()");
		if(e && e.preventDefault) { e.preventDefault(); }

		if (Juniper.sendToPhone.showing) {
			Juniper.sendToPhone.showing = false;
			Juniper.sendToPhone.panel.fadeOut(500);
		}
	},

	/*	change displayed fields
		@input: e - change click event
	*/
    changeMobileNumber: function(e) {
        ;;; console.log("Juniper.sendToPhone.changeMobileNumber()");
        if(e && e.preventDefault) { e.preventDefault(); }

        $('#currentMobile').hide();
        $('#changePhoneField').show();
    },

	/* parse through the error array and add errors to the overlay
		@input: errors - string array of errors
	*/
	parseErrors: function(errors) {
        ;;; console.log("Juniper.sendToPhone.parseErrors()");
        $('li.error', Juniper.sendToPhone.panel).remove();
        var errorStr = ''
		$.each(errors, function(i, error) {
			if (i > 0) {
                errorStr += '<br />' + error;
            } else {
                errorStr = error;
            }
		});

		$('.highlight:last', Juniper.sendToPhone.panel).after('<li class="error">'+ errorStr + '</li>');
	},

	/*	post phone info via ajax
		@input: e - submit click event
	*/
	submitPhone: function(e) {
        ;;; console.log("Juniper.sendToPhone.submitPhone()");
		if(e && e.preventDefault) { e.preventDefault(); }

        var num = null;
		var mobileNumber = $('#userMobile').val();
        var newNumber = $('#newMobileNumber').val();
		var submitUrl = '/content/'+ Juniper.sendToPhone.currentItem +'/send/to-device';

        if($('#newMobileNumber:visible').length > 0) {
            num = newNumber;
        } else {
            num = mobileNumber;
        }

        $('li.error', Juniper.sendToPhone.panel).remove();
        Juniper.sendToPhone.instructionMessage.hide();
        Juniper.sendToPhone.sendingMessage.show();
        Juniper.sendToPhone.sentMessage.hide();
        Juniper.sendToPhone.formContainer.slideUp();

        $.post(submitUrl, { 'phoneNumber': num },
            function(data) {
				if(data.success) {
                    Juniper.sendToPhone.instructionMessage.hide();
                    Juniper.sendToPhone.sendingMessage.hide();
                    Juniper.sendToPhone.sentMessage.show();

                    setTimeout("Juniper.sendToPhone.hideStatus()", 1000);

                    // tracking
                    s.linkTrackVars='prop6,prop17,prop23,prop32,products,events';
                    s.linkTrackEvents='event22';
                    s.prop32 = 'fw:sent2phone';
                    s.products = ';'+Juniper.sendToPhone.DCCID;
                    //s.products = s.products.replace(s.products.substr(s.products.indexOf(';;;;'), s.products.length), '');
                    s.events='event22';
                    s.tl(this,'o','ovi:store:fw:content sent to phone');
				} else {
                    Juniper.sendToPhone.instructionMessage.show();
                    Juniper.sendToPhone.sendingMessage.hide();
                    Juniper.sendToPhone.sentMessage.hide();
                    Juniper.sendToPhone.formContainer.show();

					Juniper.sendToPhone.parseErrors(data.errors);
				}
            },
		'json');
	},

	/*	set up listeners on clicks
	*/
	init: function(){
        ;;; console.log("Juniper.sendToPhone.init()");
		Juniper.sendToPhone.panel = $("#sendtophoneOverlay");
		Juniper.sendToPhone.instructionMessage = $(".instructionMessage", Juniper.sendToPhone.panel);
		Juniper.sendToPhone.sendingMessage = $(".sendingMessage", Juniper.sendToPhone.panel);
		Juniper.sendToPhone.sentMessage = $(".sentMessage", Juniper.sendToPhone.panel);
        Juniper.sendToPhone.formContainer = $("li.overlayActions", Juniper.sendToPhone.panel);
		$(".closer", Juniper.sendToPhone.panel).bind("click", Juniper.sendToPhone.hideStatus);
		$("#toPhoneSubmit", Juniper.sendToPhone.panel).bind("click", Juniper.sendToPhone.submitPhone);
		$(".sendViaPopup").live("click", Juniper.sendToPhone.showUpdate);
        $('#changeMobile').bind('click', Juniper.sendToPhone.changeMobileNumber);
	}
}

/** -------------------------
	page load initialize
*/
$(document).ready(function() {
    if (Juniper.global.loggedInUser) {
    	Juniper.sendToPhone.init();
    }
});
/** ------------------------- 
 * grid_tip.js
 * show tool tip on grid
 * @author: julia yu 
 */

var Juniper = window.Juniper || {};

Juniper.view = {
	current: "", 
	
	/* 	set default view based on hardcoded
	*/
	setCurrent: function(){
		if ($("#columnTwo .entityList").hasClass("listView")) {
			Juniper.view.current = "List";
		} else {
			Juniper.view.current = "Grid";
		}
		Juniper.view.toggleButtons();
	},
	
	/*	change the toggle buttons select state
		and remember what view is prefered
	*/
	toggleButtons: function(){
		Juniper.global.setCookie("view", Juniper.view.current);
		
		if (Juniper.view.current === "Grid") {
			$(".viewGrid" + " a:first").addClass("selected");
			$(".viewList" + " a:first").removeClass("selected");
		} else {
			$(".viewGrid" + " a:first").removeClass("selected");
			$(".viewList" + " a:first").addClass("selected");
		}
	},
	
	/*	change view from grid to list or whichever
		@input: type - string current view type
	*/
 	toggle: function(type, e){
        if(e && e.preventDefault) { e.preventDefault(); }

		if (type === Juniper.view.current){
			return;
		}
		Juniper.view.current = type;
		Juniper.view.toggleButtons();
		var theList = $("#columnTwo .entityList");
		theList.toggleClass("listView");
		theList.toggleClass("gridView");
	},
	
	init: function() { 
		Juniper.view.setCurrent();
		$("#views .viewGrid a:first").bind("click", function(e) {
			Juniper.view.toggle("Grid", e);
		});
		$("#views .viewList a:first").bind("click", function(e) {
			Juniper.view.toggle("List", e);
		});
	}
}

/** ------------------------- 
	page load initialize
*/
$(document).ready(function(){
	Juniper.view.init();
});
/**
 * See (http://jquery.com/).
 * @name $
 * @class
 * See the jQuery Library  (http://jquery.com/) for full details.
 * This just documents the function and classes that are added to jQuery by this plug-in.
 */

/**
 * See (http://jquery.com/)
 * @name fn
 * @class
 * See the jQuery Library  (http://jquery.com/) for full details.
 * This just documents the function and classes that are added to jQuery by this plug-in.
 * @memberOf $
 */ 
 
/**
 * Watermark Text Plugin initializes INPUT[@type=text] and TEXTAREA elements with a default value 
 * to display watermark text that will disappear when the control recieves focus
 * and reappear on blur if the control value is empty
 * 
 * @author mpaige@schematic.com
 * @memberOf $.fn
 * @name watermarkText
 * @function
 * @requires jQuery
 * @example: $(object).watermarkText();
 * @cat plugin
 * @type jQuery 
 * @version $Rev$
 */
(function($) {
    $.fn.watermarkText = function() {
        return this.each(function(){
            var defaultText = $(this).attr("title");
            $(this).focus(function() {
                if ($(this).val() === defaultText) {
                    $(this).val('');
                }
            }).blur(function() {
                if ($(this).val() === '') {
                    $(this).val(defaultText);
                }
            });
        });
    };
})(jQuery);
/* Global */

/* global.js function inventory */

/* reload captcha */
/* cookie set */
/* cookie get */
/* cookie delete */
/* subnav show/hide */
/* confirm remove/delete? */
/* spotlight (flash) interface functions */
/* language selector */

//var Void=function(){}; if(!console){var console={log:function(str){alert(str);}}}
var Void=function(){}; if(!console){var console={log:Void};}

var Juniper = window.Juniper || {};
Juniper.global = Juniper.global || {};


/**
 * Reloads the captcha image on the register page
 */
Juniper.global.reloadCaptcha = function() {
    var now = new Date();
    $('#imgCaptcha').attr('src', Juniper.global.baseURL + '/image/captcha/?' + now.getTime());
};


/* cookie set (override) */
Juniper.global.setCookie = function(cookieName, cookieValue) {
    if (typeof Juniper.global.cookieDomain === "undefined") {
        document.cookie = cookieName + "=" + cookieValue + "; path=/";
    } else {
        document.cookie = cookieName + "=" + cookieValue + "; path=/; domain=" + Juniper.global.cookieDomain;
    }
}

Juniper.global.getCookie = function(cookieName) {
    var nameEQ = cookieName + '=';
    var chip = document.cookie.split(';');

    for (var i = 0; i < chip.length; i++) {
        while (chip[i].charAt(0) == ' ') {
            chip[i] = chip[i].substring(1, chip[i].length);
        }
        if (chip[i].indexOf(nameEQ) === 0) {
            return chip[i].substring(nameEQ.length, chip[i].length);
        }
    }
    return null;
}

Juniper.global.delCookie = function(cookieName) {
	var date = new Date();
	date.setTime(-1);
	document.cookie = cookieName + '= ""; expires=' + date.toGMTString() + 'path=/; domain=' + Juniper.global.cookieDomain;
}

/*
 * Show the correct tab for the sub section selected
 */
Juniper.crumbs = {
	hidden: false,
	crumb: null,

	hideCrumb: function(){
		if (Juniper.crumbs.crumb) {
			Juniper.crumbs.hidden = true;
			Juniper.crumbs.crumb.hide();
		}
	},

	showCrumb: function(){
		if (Juniper.crumbs.crumb) {
			Juniper.crumbs.hidden = false;
			Juniper.crumbs.crumb.slideDown("slow");
		}
	},

	init: function() {
		Juniper.crumbs.crumb = $("#crumbTabs");
		if (Juniper.crumbs.crumb) {
			Juniper.crumbs.crumb.hide();
            if(!$('#contentNav').hasClass('menuOpen')) {
                Juniper.crumbs.showCrumb();
			}
		}
	}
};

/*
 * Open and close the content navigation
 */
Juniper.menu = {
    linkHandler: function(e) {
        e.preventDefault();
        Juniper.crumbs.hideCrumb();

        $('#expandedNav', '#contentNav').slideToggle('normal', function() {
            $('#contentNav').toggleClass('menuOpen');

            if($('#contentNav').hasClass('menuOpen')) {
                var menuState = 'menuOpen';
            } else {
                var menuState = '';
                Juniper.crumbs.showCrumb();
            }

    		Juniper.global.setCookie("menu", menuState);
        });
    },

    init: function() {
        $('.menuToggle', '#contentNav').live('click', Juniper.menu.linkHandler);
    }
};

/*
 * Open and Close select boxes for filter
 */
Juniper.fauxSelectBox = {
    closeSelect: function(e) {
        $('.dropdown').each(function() {
            if ($(this).hasClass('open')) {
                $(this).removeClass('open').find('.ddListOptions').hide();
            }
        });
    },

    linkHandler: function(e) {
        e.preventDefault();
        e.stopPropagation();
        $(this).next().toggle()
            .parent('.dropdown').toggleClass('open');
    },

    init: function() {
        $('a.ddListSelected', '.dropdown').live('click', Juniper.fauxSelectBox.linkHandler);
        $(window).bind('click', Juniper.fauxSelectBox.closeSelect);
    }
};


/*
 * Spotlight interface functions
 */
// Opens the phone selector when the user clicks either "Where's my phone?" or "Change Phone"
function openPhoneSelector() {
    if( Juniper.deviceSelect && Juniper.deviceSelect.showPanel ) {
        Juniper.deviceSelect.page = 'home';
        Juniper.deviceSelect.showPanel();
    }
}

// Called when the user selects "Finish Registering" in the signed out, phone set, unregistered view.
function finishRegistering() {
    if( Juniper.register && Juniper.register.showPanel ) {
        if ( Juniper.deviceSelect ) {
            Juniper.deviceSelect.page = 'home';
        }
        Juniper.register.showPanel();
    }
}

// Called when the user indicates they are selecting the current phone as theirs by clicking "I have this phone!".
// Sends an integer phone ID as the only argument.
function selectPhone( terminalId ) {
    Juniper.deviceSelect.terminalId = terminalId;
    if( Juniper.deviceSelect && Juniper.deviceSelect.setDevice ) {
        Juniper.deviceSelect.page = 'home';
      	Juniper.deviceSelect.setDevice();
    }

    //tracking
    s.products = '';
}

// Called every time a new phone is displayed at the top of the carousel
function newPhoneDisplay(terminalId, dccid) {
    Juniper.deviceSelect.terminalId = terminalId;
    if( Juniper.deviceSelect && Juniper.deviceSelect.sendTerminalId ) {
        Juniper.deviceSelect.sendTerminalId();
    }

    // tracking
    s.linkTrackVars='prop6,prop17,prop23,prop32,products,events';
    s.linkTrackEvents='event27';
    s.products=';'+ dccid;
    s.prop32='new phone selected';
    s.events='event27';
    s.tl(this,'o','ovi:store:fw:new phone selected');
}

// used only for tracking purposes
function SpotlightTracker(dccid) {
    if (dccid != '') {
        s.linkTrackVars='prop6,prop17,prop21,prop22,prop23,products,events';
        s.linkTrackEvents='event27';
        s.products=';'+ dccid;
        s.events='event27';
        s.tl(this,'o','ovi:store:fw:bso impression');
    }
}
/*
 * end Spotlight interface functions
 */

// change the language for the site
Juniper.language = {
    change: function(e) {
        e.preventDefault();

        var uri = (location.href.indexOf('#/')>-1) ? location.hash.replace(/^#/, '') : location.href;
    	var chosenLang = $("option:selected", this).val();

        $.get(uri, {lang: chosenLang},
            function() {
                window.location.replace(uri);
            });
    }
};

Juniper.contentDetail = {
    init: function() {
        var $previewContainer = $('#previewItem');
        var $preview = $('.preview img', $previewContainer);
        var osrc = $preview.attr('src');

        $('.thumb a', $previewContainer).bind('click mouseover focus', function(e) {
            e.preventDefault();
            $preview.attr('src', this.href);
        });
        /*.bind('mouseout blur', function(e) {
            $preview.attr('src', osrc);
        });*/
    }
};

Juniper.installClient = {
    init: function(){
        var $container = $('#install_client');
        var $close = $('.close', $container);
        
        $close.click(function() {
            $container.fadeOut();
        });
    } 
}

$(document).ready(function() {
	/* handle specific link types */
	// launch new window with link's href, replaces target attr
	$("a.newWindow").click(function(e) {
		newWin = window.open(e.target.href);
        newWin.focus();
	});

	// go back a page
	$("a#back").click(function(e) {
		window.history.back();
	});

	/* sub-nav rollovers on landing page */
    //Juniper.subNav.init();
    Juniper.menu.init();

    Juniper.fauxSelectBox.init();

    /* init search box with watermark text */
    $("#search").watermarkText();

	$("#langSetting").bind("change", Juniper.language.change);
	
	$('.overflow').ellipsis();

    Juniper.contentDetail.init();
    
    Juniper.installClient.init();
});
