/* Declare a namespace for the site */
var site = window.site || {};

/* Create a closure to maintain scope of the '$'
   and remain compatible with other frameworks.  */
(function($) {
	
	//same as $(document).ready();
	$(function() {

        /**
         * Functions for dealing with search
         *
         * Mostly to do with adding and removing facets
         */
		site.search = {

            /**
             * @var array A list of facets
             */
            facets: [],

            /**
             * @var string The query processed
             */
            query: '',

            /**
             * Makes sure that facets and query properties are populated
             */
            init: function() {
                site.search.facets = site.search.parseSelectedFacets();
                site.search.query = site.search.parseQuery();
                $("#id_q").autocomplete({
                    source: "/search/autocomplete/",
                    minLength: 3,
                    select: function( event, ui) {
                        $('#id_q').val(ui.item.label);
                        if (ui.item && ui.item.value) {
                            location.href = ui.item.value;
                        }
                        return false; //prevent the value being put into the text field
                    },
                    focus: function( event, ui) {
                        $('#id_q').val(ui.item.label);
                        return false;
                    }
                });

            },

            /**
             * Parses selected facets from hidden field
             *
             * @return array
             */
            parseSelectedFacets: function() {
                var selectedFacets = [];
                if ($('#id_selected_facets') && $('#id_selected_facets').val() !== undefined && $('#id_selected_facets').val().length != 0) {
                    selectedFacets = $('#id_selected_facets').val().split('|');
                    for (var i=0; i<selectedFacets.length; i++) {
                        selectedFacets[i] = encodeURI(selectedFacets[i]);
                    }
                }
                return selectedFacets;
            },

            /**
             * Grabs the current query
             *
             * @return string
             */
            parseQuery: function() {
                var query = '';
                if ($('#id_q')) {
                    query = $('#id_q').val();
                }
                return query;
            },

            /**
             * Adds a facet to the stack
             */
            addFacet: function(facet, value) {
                if (-1 != value.indexOf(' ')) {
                    //facets with spaces must be quoted
                    value = '"' + value + '"';
                }
                var facetToAdd = encodeURI(facet + '_exact:' + value);
                if (-1 == jQuery.inArray(facetToAdd, site.search.facets)) {
                    site.search.facets[site.search.facets.length] = facetToAdd;
                }
                site.search.search();
            },

            /**
             * removes a facet from the stack
             */
            removeFacet: function(facet, value) {
                if (-1 != value.indexOf(' ')) {
                    //facets with spaces must be quoted
                    value = '"' + value + '"';
                }
                var facetToRemove = encodeURI(facet + '_exact:' + value);
                site.search.facets = jQuery.map(site.search.facets, function(item, index) {
                    if (facetToRemove == item) {
                        return null;
                    }
                    return item;
                });
                site.search.search();
            },

            /**
             * Removes all facets applied within a specific group
             **/
            clearFacet: function(facet)
            {
                facet = facet + "_exact:";
                site.search.facets = jQuery.map(site.search.facets, function(item, index) {
                    if (item.indexOf(facet) === 0) {
                        return null;
                    }
                    return item;
                });
                site.search.search();
            },

            /**
             * Clears all facets
             **/
            clearFacets: function() {
                site.search.facets = [];
                site.search.search();
            },

            /**
             * kicks off a search
             *
             * Pull query and facets from the stack
             */
            search: function() {
                var facets = '';
                if (site.search.facets.length > 0) {
                    facets = "&selected_facets=" + site.search.facets.join('|');
                }
                var params = "q=" + encodeURI((site.search.parseQuery())) + facets;
                location.href = "http://" + location.host + '/library/?' + params;
            },

            switch_display_mode: function(display_mode) {
                $.ajax({
                    type: "GET",
                    url: '/search/switch-display-mode/',
                    data: "display_mode=" + display_mode,
                    success: function(msg){
                        location.href = location.href; //
                    }
                });
            }


        };



        site.mascot = {

            included: false,

            init: function() {
                $("#mascot").click(function() {
                    if (!site.mascot.included) {
                        site.mascot.include_resources();
                    } else {
                        snake.toggle();
                    }
                });
            },

            include_resources: function() {
                if (!site.mascot.included && screen.width > 992) {
                    var link = $("<link>");
                    link.attr({
                        type: 'text/css',
                        rel: 'stylesheet',
                        href: '/media/css/snake.css'
                    });
                    $("head").append( link );
                    var js = $("<script>");
                    js.attr({
                        type: 'text/javascript',
                        src: '/media/js/snake.js'
                    });
                    $("head").append(js);
                    site.mascot.included = true;
                }
            }

        };


				site.homepage = {
					
					init: function() {
						
						if (screen.width < 480) { // if it is a small screen device or mobile phone
							$("#homepage_carousel").remove();
							$("#homepage_quicklinks").remove();
							$("#mascot").remove();
							$("#spotlight").remove();
						} else {
							if ($("#homepage_work") && $("homepage_blog")) {
								$("#homepage_work .carousel").jCarouselLite({
									btnNext: "#homepage_work .next",
									btnPrev: "#homepage_work .prev",
									speed: 500,
									circular: true,
									visible: 1,
									touchNavigation: true,
									easing: 'easeinout'
								});

								$("#homepage_blog .carousel").jCarouselLite({
									btnNext: "#homepage_blog .next",
									btnPrev: "#homepage_blog .prev",
									speed: 500,
									circular: true,
									visible: 1,
									touchNavigation: true,
									easing: 'easeinout'
								});

								var oldHtml;
								$(".homepage_blog h1 a").hover(
									function() {
										oldHtml = $(this).html();
										$(this).html("View all blog posts");
										$(this).css("cursor","pointer");
									},
									function() {
										$(this).html(oldHtml);
									}
								);

								$(".homepage_work h1 a").hover(
									function() {
										oldHtml = $(this).html();
										$(this).html("View all projects");
										$(this).css("cursor","pointer");
									},
									function() {
										$(this).html(oldHtml);
									}
								);

							}
						};

						$('img').retina();
					}
				};
				
				site.profiles = {
					
					init: function() {
						if (screen.width < 768) { // if it is a small screen device or mobile phone
							
						} else {
							if ($("#profile_blog_posts")) {
								$("#profile_blog_posts .carousel").jCarouselLite({
									btnNext: "#profile_blog_posts .next",
									btnPrev: "#profile_blog_posts .prev",
									speed: 500,
									circular: false,
									visible: 3,
									touchNavigation: true,
									easing: 'easeinout'
								});
							};
						
							if ($("#profile_projects")) {
								$("#profile_projects .carousel").jCarouselLite({
									btnNext: "#profile_projects .next",
									btnPrev: "#profile_projects .prev",
									speed: 500,
									circular: false,
									visible: 3,
									touchNavigation: true,
									easing: 'easeinout'
								});
							};
						}
					}
				};
				
				site.profiles_slider = {
					init: function() {
						
						
						
						//scrollpane parts
						var scrollPane = $( ".scroll-pane" ),
							scrollContent = $( ".scroll-content" );

						//build slider
						var scrollbar = $( ".scroll-bar" ).slider({
							slide: function( event, ui ) {
								if ( scrollContent.width() > scrollPane.width() ) {
									scrollContent.css( "margin-left", Math.round(
										ui.value / 100 * ( scrollPane.width() - scrollContent.width() )
									) + "px" );
									$(".mascot_f").css("left", 240+ Math.round(
										ui.value / 120 * ( scrollPane.width() - scrollContent.width() )
									) + "px");
									$(".mascot_m").css("left", 1000+ Math.round(
										ui.value / 120 * ( scrollPane.width() - scrollContent.width() )
									) + "px");
/*									$("#breathe").text(ui.value / 100 * ( scrollPane.width() - scrollContent.width()));*/
								} else {
									scrollContent.css( "margin-left", 0 );
								}
							}
						});
						
						
						if(jQuery().swipe) {
							function swipeStatus(event, phase, direction, distance)
							{
								var value = $( ".scroll-bar" ).slider( "option", "value" );
								//If we are moving before swipe, and we are going Lor R in X mode, or U or D in Y mode then drag.
								if( phase=="move" && (direction=="left" || direction=="right") )
								{
									if (direction == "left") {
										scrollContent.css( "margin-left", (value/100 * (scrollPane.width() - scrollContent.width()) ) -distance + "px" );
										resetValue();
									}
									else if (direction == "right") {
										scrollContent.css( "margin-left", (value/100 * (scrollPane.width() - scrollContent.width()) ) +distance + "px" );
										resetValue();
									}
									

																			
									if(scrollContent.offset().left >0) {
/*										scrollContent.animate({marginLeft: 0},'5000','elasout');*/
										scrollContent.css( "margin-left", 0);
									} else if(scrollContent.offset().left < -scrollContent.width() +scrollPane.width()) {
/*										scrollContent.animate({marginLeft: -scrollContent.width() +scrollPane.width()},'3000','elasout');*/
										scrollContent.css( "margin-left", -scrollContent.width() +scrollPane.width() + "px");
									}
																		
/*									var value = $( ".scroll-bar" ).slider( "option", "value" );*/
/*									$("#breathe").text(-(Math.round( scrollPane.width() - scrollContent.width() * distance)/100) );*/
/*									$("#breathe").text(scrollContent.offset().left);*/
/*									$("#breathe").text(Math.round(distance/scrollPane.width() * 100));*/

								}
							}
						// swipe plugin exists, so we can now call it
						// scrollPane.swipe({
						// 							allowPageScroll: 'vertical',
						// 							swipeStatus : swipeStatus,
						// 							threshold:0
						// 							});
							
							
						}
					
						

						// scrollContent.width("1630px");
						scrollContent.width(scrollContent.children(".scroll-content-item").outerWidth(true) * $(".scroll-content-item").length +"px");

						//append icon to handle
						var handleHelper = scrollbar.find( ".ui-slider-handle" )
						.append( "<span class='ui-icon ui-icon-grip-dotted-vertical'></span>" )
						.wrap( "<div class='ui-handle-helper-parent'></div>" ).parent();

						//change overflow to hidden now that slider handles the scrolling
						scrollPane.css( "overflow", "hidden" );
						$(".scroll-content-item a").each(function() {
							$(this).css("background-image", "url(" + $(this).children("img").attr("src") + ")");
							$(this).children("img").remove();
						});
						

						if(!$("#ToolTipDiv").length){
							$("body").append("<div id='ToolTipDiv'></div>");
						} 
						
						$("h2.profile_name").hide();
						$("h3.profile_position").hide();
						
						// $("#ToolTipDiv").append("<div class='arrow''>&#9670; <div class='mask'>&nbsp;</div></div>");
						$(".scroll-content-item a").hover(
							function(event) {
								$(this).mousemove(function(event) {
									var tipY = event.pageY + 24;
									var tipX = event.pageX + 0;
									$("#ToolTipDiv").css({'top': tipY, 'left': tipX});
								});
								$("#ToolTipDiv")
									.html("<div class=\'arrow\'>&#9670;</div><strong>"+$(this).children("h2.profile_name").html()+"</strong><br />"+$(this).children("h3.profile_position").html())
									.stop(true,true)
									.fadeIn("fast");
							},
							function(event) {
								$("#ToolTipDiv")
									.stop(true,true)
									.fadeOut("fast");
							}
						);

						//size scrollbar and handle proportionally to scroll distance
						function sizeScrollbar() {
							// uncomment for proportional scroll handle
/*							var remainder = scrollContent.width() - scrollPane.width();*/
/*							var proportion = remainder / scrollContent.width();*/
/*							var handleSize = scrollPane.width() - ( proportion * scrollPane.width() );*/

							// fixed-size (80px) scroll handle
/*							var remainder = scrollPane.width() - 80;*/
/*							var proportion = remainder / scrollPane.width();*/
							var handleSize = 80;
/*							var handleSize = scrollPane.width() - ( proportion * scrollPane.width() );*/

							scrollbar.find( ".ui-slider-handle" ).css({
								width: handleSize,
								"margin-left": -handleSize / 2
							});
/*							handleHelper.width( "" ).width( scrollbar.width() - handleSize );*/
							handleHelper.width( "" ).width( scrollbar.width() - handleSize );
							if(scrollPane.width() > scrollContent.width()) {
								scrollbar.find( ".ui-slider-handle" ).hide();
							} else {
								scrollbar.find( ".ui-slider-handle" ).show();
							}

						}



						//reset slider value based on scroll content position
						function resetValue() {
							var remainder = scrollPane.width() - scrollContent.width();
							var leftVal = scrollContent.css( "margin-left" ) === "auto" ? 0 :
								parseInt( scrollContent.css( "margin-left" ) );
							var percentage = Math.round( leftVal / remainder * 100 );
							scrollbar.slider( "value", percentage );
						}

						//if the slider is 100% and window gets larger, reveal content
						function reflowContent() {
								var showing = scrollContent.width() + parseInt( scrollContent.css( "margin-left" ), 10 );
								var gap = scrollPane.width() - showing;
								if ( gap > 0 ) {
									scrollContent.css( "margin-left", parseInt( scrollContent.css( "margin-left" ), 10 ) + gap );
								}
						}

						//change handle position on window resize
						$( window ).resize(function() {
							resetValue();
							sizeScrollbar();
							reflowContent();
						});
						//init scrollbar size
						setTimeout( sizeScrollbar, 10 );//safari wants a timeout
					}
				};
				
				

				site.services = {
					
					init: function() {
						if(!$("#ToolTipDiv").length){
							$("body").append("<div id='ToolTipDiv'></div>");
						}
						
						if($(".services")) {
							$(".services a").hover(
								function(event) {
									$(this).mousemove(function(event) {
										var tipY = event.pageY + 24;
										var tipX = event.pageX - 16;
										$("#ToolTipDiv").css({'top': tipY, 'left': tipX});
									});
									$("#ToolTipDiv")
										.html("<div class=\'arrow\'>&#9670;</div>"+$(this).children("img").attr("alt"))
										.stop(true,true)
										.fadeIn("fast");
								},
								function(event) {
									$("#ToolTipDiv")
										.stop(true,true)
										.fadeOut("fast");
								}
							);
						}
					}
				};
				
		
		if($("#banner_image")) {
			$("#banner_image").hover(
				function() {
					
					$("#customer_logos").fadeIn();
				},
				function() {
					$("#customer_logos").fadeOut();
				}
			);
		};
		
		
		site.solutions = {
			
			init: function() {
				
				if(screen.width < 768) {
					$("#solutions_banner").remove();
				} else {
					if ($("#taoshop_features")) {
						$("#taoshop_features .carousel").jCarouselLite({
							btnNext: "#taoshop_features .navigator .next",
							btnPrev: "#taoshop_features .navigator .prev",
							speed: 500,
							circular: false,
							visible: 4,
							touchNavigation: true,
							easing: 'easeinout'
						});
					};
				}
			}
		};



		/* Kick everything off as soon as the DOM is ready */

		// load up stuff on the homepage
		site.homepage.init();
		

		//bootstrap the search 
		site.search.init();
		//init the snake game hidden in the mascot
		site.mascot.init();

		site.services.init();
		
		if(screen.width < 768) {
			$("#join_us_shoes").remove();
			$("#slider-frame").remove();
			$("#breathe").remove();
		} else {
			site.profiles.init();
			site.profiles_slider.init();
		}
		
		site.solutions.init();

	});


	$(window).bind("load", function() {
		/* Stuff to do on window.load (when all images and external assets are loaded) */
	
	
		if ($("#homepage_carousel")) {
			$("#homepage_carousel .carousel").jCarouselLite({
				btnNext: "#homepage_carousel .next",
				btnPrev: "#homepage_carousel .prev",
				auto: 4000,
				speed: 500,
				circular: true,
				visible: 1,
				pauseOnHover: true,
				touchNavigation: true,
				easing: 'easeinout',
				afterEnd: function(item) {

					currPage = item.index() -1;
					if (currPage == ($("#homepage_carousel li").length -2)) {
						currPage = 0;
					}
					$("#carousel_paginator span").removeClass("selected");
					$("#carousel_paginator span").eq(currPage).addClass("selected");
				}
				
/*				$('#homepage_carousel .carousel li').fadeIn();*/
			});
			
			
				var n = $("#homepage_carousel li").length -2;
				var i=0;
				for (i=0;i<n;i++)
				{
					$("#carousel_paginator").append("<span>&bull;</span>");
					$("#carousel_paginator span").first().addClass("selected");
				}
				


			
		}
		
		
		//init the carousels on profile detail page
		site.profiles.init();
		
		
	});
	
})(jQuery);


