//	Search init

(function($) {

    $.search = $.search || {};

    var g_ready = false;
    var g_self = this;

    $.fn.search = function() {
        return this.each(function() {
            //alert("API method called on " + this);
        });
    };

    $.search.init = function(options) {
        var c_self = this;
        var c_ready = false;
        c_self.options = $.extend({}, $.search.init.searchs, options);

        c_self.functions = {
            initialise: function(context) {
                context.each(function(index) {

                });
            },
            setupScroll: function() {
				$(".scroll ul").scrollWindow();
				if (_IE6){
					$('body').pngFix();
				};
            },
            setupCheckboxes: function() {
				
				$("#event-filters .filter").find(".options").each(function(i){
					if($(this).children("ul").length != 0){
						
						// Also check that they are checkboxes?
						
						var parentBox = $(this).find(".header label input[@type=checkbox]");
						var childrenContainer = $(this).find("ul");
						var childrenBox = childrenContainer.find("input[@type=checkbox]");

						parentBox.click(function(){
							if($(this).is(":checked")){
								childrenContainer.checkCheckboxes();
							} else {
								childrenContainer.unCheckCheckboxes();
							}
						});
						
						childrenBox.click(function(){
							
							// if there are no checkboxes inside the container that are checked
							if(childrenContainer.find("input[@type=checkbox]").is(":checked")){
								parentBox.parent().checkCheckboxes();
							} else {
								parentBox.parent().unCheckCheckboxes();
							}

						});
												
					}
				});
				
            },
            setupCompare: function() { // re-written to compensate for new logic
            
				
				
            
				var ready = true; // set ready var
				var selectedPhones = []; // array of selected items
				
				// Core identifiers
				var filteredList = $(".search-phones-rep ul") // filtered phones container
				var comparisonList = $(".compare-phones-wrap ul") // comparison container
				
				//Localised text
				var textCompare = $(".search-phones-rep li label span:first").text();
				
				// Html elements
				var emptyBoxHTML = $("<li class=\"empty\"><div class=\"phone\"><span class=\"phone-top\"/><div class=\"phone-data\"><p>Empty</p></div><span class=\"phone-bot\"/></div><span class=\"remove-compare\"/></li>");
				var compareButtonHTML = $("<a class=\"plus add-compare button\"><span><span><span><span><span>" + textCompare + "</span></span></span></span></span></a>");
				var removeButtonHTML = $("<span class=\"remove-compare\"/>");
				var clearButtonHTML = $("<a title=\"Clear selection\" class=\"button x\"><span><span><span><span><span>Clear selection</span></span></span></span></span></a>");
				
				// setup compare submit
				var compareSubmit = $(".compare-button").remove();
				$(".compare-info").append(compareSubmit);
				$(".compare-button").buttonSwap("ra compare-button selected");
				
				filteredList.find("li").each(function(){
					setupPhone(this);
				});
				
				comparisonList.find("li:not(.empty)").each(function(){
					var comparedPhoneName = $(this).find(".phone-name-short").text();
					selectedPhones.unshift(comparedPhoneName);
					setupCompareItem(this);
				});
				
				function setupPhone(phoneElement){
				
					var phoneItem = $(phoneElement);
					phoneItem.phoneNameText = phoneItem.find(".phone-name-short").text();
					
					//trace(" :: setupPhone " + phoneItem.phoneNameText)
					
					// Configure compare item
					// First check to see if a compare item already exists in the comparison container 
					if(comparisonList.find("li:contains('"+phoneItem.phoneNameText+"')").length == 1) {
						phoneItem.comparePhone = comparisonList.find("li:contains('"+phoneItem.phoneNameText+"')");
						phoneItem.phoneSelect = phoneItem.comparePhone.find("input:checkbox"); // get related checkbox for phone
						phoneItem.comparePhone.find("input").attr("value", "Selected_"+phoneItem.phoneNameText); // modify the compare checkbox for ASP
						phoneItem.comparePhone.find(".new-badge").remove(); // if theres a "new tag" then remove it
						phoneItem.removeButton = phoneItem.comparePhone.find(".remove-compare"); // remove button
					// If there is not already a compare item, create it
					} else {
						phoneItem.comparePhone = phoneItem.clone();
						phoneItem.phoneSelect = phoneItem.comparePhone.find("input:checkbox"); // get related checkbox for phone
						phoneItem.comparePhone.find("input").attr("value", "Selected_"+phoneItem.phoneNameText); // modify the compare checkbox for ASP
						
						phoneItem.comparePhone.find(".new-badge").remove(); // if theres a "new tag" then remove it
						phoneItem.removeButton = removeButtonHTML.clone(); // create remove button
						phoneItem.comparePhone.append(phoneItem.removeButton); // add the remove button
						
						if(_IE6){
							var imgSrc = phoneItem.comparePhone.find(".phone-image img").attr("src");
							var imgSrcMod = imgSrc.split("png")[0] + "jpg";
							//alert(imgSrcMod)
							phoneItem.comparePhone.find(".phone-image").html("<img />");
							phoneItem.comparePhone.find(".phone-image img").attr("src", imgSrcMod);
						}
						
					}
					
					// Cleanup original
					phoneItem.find("label").remove(); // remove checkbox
					
					// Add compare button
					phoneItem.compareButton = compareButtonHTML.clone(); // create compare button
					phoneItem.find(".phone").after(phoneItem.compareButton) // add to the page
					phoneItem.compareButtonText = phoneItem.compareButton.find("span:last");
					
					phoneItem.compareButton.click(function(){
					
						//trace(" > Compare Clicked ")
						//alert(selectedPhones)
						if(ready){
							//trace(phoneItem.phoneSelect)
							if(phoneItem.phoneSelect.is(":checked")){
								phoneItem.phoneSelect.click();
								removeItem(false, phoneItem);
							} else {
								if(selectedPhones.length < 3){
									addItem(true, phoneItem);
								} else {
									// get the first item from array (as it will be the last added) and associated vars
									// this could have broken, however "unshift" works nice
										
									var firstItem = filteredList.find("li:contains('"+selectedPhones[0]+"')");
									//alert(firstItem.length)
									if(firstItem.length == 1){
										var firstItemButton = firstItem.find(".add-compare");
										var firstItemButtonText = firstItemButton.find("span:last");
										// modded slightly to get the checkbox from the compare box
										var firstItemCompare = comparisonList.find("li:contains('"+selectedPhones[0]+"')");
										var firstItemSelect = firstItemCompare.find("input:checkbox");
										
										firstItemSelect.click(); // run a click action on that items checkbox
										//alert(firstItemSelect.parent().html());
										
										firstItemButton.removeClass("selected"); // remove selected class from button
										firstItemButtonText.text(textCompare); // change button text
									}
									
									removeArrayItem(selectedPhones, selectedPhones[0]); // remove item from array
									addItem(true, phoneItem);
									//alert(firstItemSelect.parent().html());
								};
								phoneItem.phoneSelect.click();
								
								if(_IE6){ // IE6 not preserving correct checked state, could replace above method with this for all browsers... 
									phoneItem.phoneSelect[0].checked = true;
									//alert(phoneItem.comparePhone.html())
								}
							};
						};
						checkStatus();
					});
					
				};
				
				function setupCompareItem(phoneElement){
				
					var comparePhone = $(phoneElement);
					comparePhone.phoneNameText = comparePhone.find(".phone-name-short").text();
					
					//trace(" :: setupComparePhone " + comparePhone.phoneNameText)
					
					comparePhone.removeButton = comparePhone.find(".remove-compare"); // remove button
					comparePhone.phoneSelect = comparePhone.find("input:checkbox"); // get related checkbox for phone
					
					var existingItem = filteredList.find("li:contains('"+comparePhone.phoneNameText+"')");
					
					if(existingItem.length == 1){
						//trace("exists in filter ")
						
						comparePhone.compareButton = existingItem.find(".add-compare"); // compare button
						comparePhone.compareButtonText = comparePhone.compareButton.find("span:last");
						
						comparePhone.compareButton.addClass("selected"); // add class to button
						comparePhone.compareButtonText.text("Remove"); // change button text
						
					};
					
					comparePhone.removeButton.click(function(){
						comparePhone.phoneSelect.click();
						removeItem(false, comparePhone);
					})
					
					checkStatus();
				
				};
				
				function addItem(animate, phoneItem){
				
					//trace(" [addItem] ");
					//trace(selectedPhones);
					
					/*
					
						animate:bool
						,
						phoneItem.phoneNameText
						phoneItem.comparePhone
						phoneItem.compareButton
						phoneItem.compareButtonText
						
					*/
					
					ready = false; // disable ready to prevent duplicate animations
					$(".add-compare.button").css({opacity: 0.4, cursor: "default"}) // alpha out all compare buttons
					
					selectedPhones.push(phoneItem.phoneNameText); // push phone to selected array
					
					phoneItem.compareButton.addClass("selected"); // add class to button
					phoneItem.compareButtonText.text("Remove"); // change button text
					
					// get the last LI 
					var compareBox = $(comparisonList.find("li:last"));
											
					// if animate is set to true then animate the boxes in
					if(animate){
						// animate out last box
						compareBox.animate({opacity: 0, marginTop: "100px"}, 350, "easeOutQuad", function(){
							compareBox.remove(); // remove container
							if(_IE6){
								
								if(!compareBox.hasClass("empty")){
									compareBox.find("input:checkbox")[0].checked = false;
									//alert(compareBox.html());	
								}
							}
							compareBox.animate({opacity: 1, marginTop: "0" },0); // reset animation vars
						});
						// animate in new box
						phoneItem.comparePhone.animate({opacity: 0, marginLeft: "-100px"}, 0, function(){
							comparisonList.prepend(phoneItem.comparePhone); // add to container
							phoneItem.comparePhone.animate({opacity: 1, marginLeft: "15px"}, 450, "easeOutQuad", function(){
								$(".add-compare.button").css({opacity: 1, cursor: "pointer"}) // reinstate buttons
								ready = true; // reinstate click functions
							});
						});
						
					// quick add of items to prevent issues getting the last container above
					} else {
						compareBox.remove();
						comparisonList.prepend(phoneItem.comparePhone)
						$(".add-compare.button").css({opacity: 1, cursor: "pointer"})
						ready = true;
					};
					
					// would be better if this wasnt here?
					phoneItem.removeButton.click(function(){
						phoneItem.phoneSelect.click();
						removeItem(false, phoneItem);
					})
					
				};
				
				
				function removeItem(animate, phoneItem){
				
					//trace(" [removeItem] ")
					//trace(selectedPhones);
					
					/*
					
						animate:bool
						,
						phoneItem.phoneNameText
						phoneItem.compareButton
						phoneItem.compareButtonText
						
					*/
					
					removeArrayItem(selectedPhones, phoneItem.phoneNameText); // remove item from array

					if(phoneItem.compareButton != null){
						phoneItem.compareButton.removeClass("selected"); // remove selected class from button
						phoneItem.compareButtonText.text(textCompare); // change button text
					}
					
					// get associated compare box
					var compareBox = $(comparisonList.find("li:contains('"+ phoneItem.phoneNameText+"')"));
					var compareContents = compareBox.find(".phone");
					
					// clone the empty box
					emptyBox = emptyBoxHTML.clone();
					//trace(compareBox);
					
					if(animate){ 
						// NOT currently being used by anything
						compareBox.animate({opacity: 0}, 350, function(){
							compareBox.remove();
							
							emptyBox.animate({opacity: 0}, 0);
							comparisonList.append(emptyBox);
							emptyBox.animate({opacity: 1}, 500, function(){

							});
							
							compareBox.animate({opacity: 1}, 0);
						})
					} else {
						compareBox.remove();
						comparisonList.append(emptyBox);
					};
					

					if(_IE6){ // IE6 not preserving correct checked state, could replace above method with this for all browsers...
						phoneItem.phoneSelect[0].checked = false;
						//alert(phoneItem.phoneSelect[0].checked);
						//alert(phoneItem.comparePhone.html())
					}
					
					
					
				};
				
				
				function checkStatus(){

					if(selectedPhones != 0){
						
						//trace("showing buttons")
						
						if($(".compare-buttons .button.x").length == 0){
							//trace("adding.. ")
							
							var clearButton = clearButtonHTML;
							$(".compare-buttons").append(clearButton);
							clearButton.css("display", "none");
							clearButton.animate({opacity: 0},0);
						} else {
							var clearButton = $(".compare-buttons .button.x");
						}					
						
						clearButton.click(function(){
							for(i in selectedPhones){
								var item = comparisonList.find("li:contains('"+selectedPhones[i]+"')");
								var itemButton = item.find(".remove-compare");
								itemButton.click();
								checkStatus();
							};
						});						
						
						if($("a.button.compare-button, .compare-buttons .button.x").css("opacity") == 0){
							$(".button.compare-button, .compare-buttons .button.x").css({display: "block"});						
							$(".button.compare-button, .compare-buttons .button.x").animate({opacity: 1},500);
						}
						
					} else {
						
						$("a.button.compare-button, .compare-buttons .button.x").css({display: "none",opacity: 0});

					};
					
					
					
				};
				
				checkStatus();
				
			}
        };
        
        c_self.functions.initialise($("body"));
        c_self.functions.setupScroll();
        c_self.functions.setupCompare();
        //c_self.functions.setupCheckboxes();
        c_ready = true;
    };
    
    // This is quick to type: trace("my console text")
    function trace(logtext) {
		try {
			if (console && console.log) {
				console.log(logtext);
			}
		} catch (err) {
			//alert(err);
		}
	};
	
	// handy item remove from array function
	function removeArrayItem(originalArray, itemToRemove) {
		var j = 0;
		while (j < originalArray.length) {
			if (originalArray[j] == itemToRemove) {
				originalArray.splice(j, 1);
			} else { j++; }
		}
		return originalArray;
	}
	
	// get array position
	function getArrayPosition(arrayName,arrayItem) {
		for(var i=0;i<arrayName.length;i++){ 
			if(arrayName[i]==arrayItem)
			return i;
		}
	};

    // handsets
    $.search.init.defaults = {};

    // initialise one or more instances of the class
    $(document).ready(function() {
        new $.search.init();
        
        $(".update-button").buttonSwap("ra selected");
        $(".clear-compare").buttonSwap("x");
        $(".phone-change").buttonSwap("ra selected");
        
    });
})(jQuery);

