var SiteLib = {};
SiteLib.Util = {};

$(function() {
  Cufon.replace('h1, h2', {
    letterSpacing: '-1px'
  });
  
	$(document).ajaxError(function(e, xhr, settings, exception) {
		alert('Error whilst fetching the required info, please try again.');
		$(".ajax_loading").remove();
	});
	
  $("body").addClass("jsEn");
  
  $("div#header p.text-size-controls a").click(function() {
		$.getJSON(MIYOLib._conf.siteBaseURL+'/accessibility/textsize/' + $(this).attr("class") + '/?mode=ajax', function(data) {
			$("body")
				.removeClass("small")
				.removeClass("medium")
				.removeClass("large")
				.addClass(data.text_size);
		});
			
		return false;
	});
	
  $("a[href^=http://]")
  	.not("[href^="+MIYOLib._conf.siteBaseURL+"]")
  	.each(function() {
  			this.target = "_blank";
  	});
  
  $("a.external").each(function() {
    this.target = "_blank";
  });
  
  initExpandableSections();
  initImpactBlocks();
	initIntroBlock();
	initSubscribeSelectAll();
});

function initExpandableSections() {
  $(".expandable-rounded").each(function() {
    var parentHold = this;
    parentHold.collapseOthers = false;
    
    if($(parentHold).hasClass("collapse-others")) {
      parentHold.collapseOthers = true;
      parentHold.$otherExpandables = $(parentHold).parent().find(".expandable-rounded");
    }
    
    parentHold.$blockHead = $(parentHold).find(".block-header:first").not(".sub-expandable .block-header")
      .css("cursor", "pointer")
      .click(function() {
        var headerRef = this;
        headerRef.originallyHadClass = true;
        
        if(!$(parentHold).hasClass("open")) {
          $(parentHold).find(".initial-content").css("display", "none");
          headerRef.originallyHadClass = false;
          
          if(parentHold.collapseOthers) {
            if(parentHold.$otherExpandables.length > 0) {
              parentHold.$otherExpandables.each(function() {
                var expandElement = this;
                
                if($(expandElement).hasClass("open")) {
                  $(expandElement).find(".expanded-content:first").slideToggle(600, function() {
                    $(expandElement).removeClass("open");
                    $(expandElement).find(".initial-content").css("display", "block");
                  });
                }
              });
            }
          }
        }
        
        $(parentHold).find(".expanded-content:first").slideToggle(600, function() {
          if(headerRef.originallyHadClass && $(parentHold).hasClass("open")) {
            $(parentHold).removeClass("open");
            $(parentHold).find(".initial-content").css("display", "block");
          } else if(!headerRef.originallyHadClass && !$(parentHold).hasClass("open")) {
            $(parentHold).addClass("open");
          }
        });
        
        return false;
      });
  });
  
  $(".sub-expandable").each(function() {
    var subExpandHold = this;
    subExpandHold.collapseOthers = false;

    if($(subExpandHold).hasClass("collapse-others")) {
      subExpandHold.collapseOthers = true;
      subExpandHold.$otherExpandables = $(subExpandHold).parent().find(".sub-expandable");
    }

    subExpandHold.$blockHead = $(subExpandHold).find(".block-header:first")
      .css("cursor", "pointer")
      .click(function() {
        var subHeaderRef = this;
        subHeaderRef.originallyHadClass = true;

        if(!$(subExpandHold).hasClass("open")) {
          $(subExpandHold).find(".initial-content").css("display", "none");
          subHeaderRef.originallyHadClass = false;
          
          if(subExpandHold.collapseOthers) {
            if(subExpandHold.$otherExpandables.length > 0) {
              subExpandHold.$otherExpandables.each(function() {
                var expandElement = this;

                if($(expandElement).hasClass("open")) {
                  $(expandElement).find(".sub-expand-content:first").slideToggle(600, function() {
                    $(expandElement).removeClass("open");
                    $(expandElement).find(".initial-content").css("display", "block");
                  });
                }
              });
            }
          }
        }

        $(subExpandHold).find(".sub-expand-content:first").slideToggle(600, function() {
          if(subHeaderRef.originallyHadClass && $(subExpandHold).hasClass("open")) {
            $(subExpandHold).removeClass("open");
            $(subExpandHold).find(".initial-content").css("display", "block");
          } else if(!subHeaderRef.originallyHadClass && !$(subExpandHold).hasClass("open")) {
            $(subExpandHold).addClass("open");
          }
        });

        return false;
      });
  });
}

function initImpactBlocks() {
  $(".impact-block-hold .impact-block").each(function() {
    $statList = $(this).find("div.stat-holder ul.stat-list");
    $statNavEntries = $(this).find("ul.stat-nav li a");
    
    $statNavEntries.each(function() {
      var origID = $(this).parent().attr("id");
			var numericChoice = origID.substring((origID.lastIndexOf("-") + 1), origID.length);
      
      $(this).click(function() {
        $statNavEntries.each(function() {
  				if($(this).parent().attr("id") != 'stat-link-'+numericChoice) {
  					if($(this).parent().hasClass("selected")) { $(this).parent().removeClass("selected") }
  				} else {
  					if(!$(this).parent().hasClass("selected")) { $(this).parent().addClass("selected") }
  				}
  			});

  			var leftVal = ((numericChoice - 1) * 344)

  			$statList.css("left", "-"+leftVal+"px");

  			return false;
      });
    });
  });
}

function initIntroBlock() {
  var animRefs = {};
  
  $("div#section-intro-block").each(function() {
    var introBlockRef = this;
    
    $(introBlockRef).find("div#intro-block-copy div.tabbed-options a").each(function() {
      var selfRef = this;
      var $tabbedOptions = $("div#section-intro-block div.tabbed-options");
      var tabs = new Array('main', 'connect', 'consult', 'communicate');
    
      var elemID = $(selfRef).attr("id");
      var tabLink = elemID.substring(0, elemID.indexOf("-"));
    
      var swapContent = function(section) {
        var $mainBlock = $("div#main-block");
        var $targetCopy = $("div#"+section+"-intro-block-copy");
        var $targetCarosel = $("div#"+section+"-carosel");
      
        for(tab_section in tabs) {
          var tabName = tabs[tab_section];
          if(tabName != section) {
            if(tabName == 'main' || $mainBlock.hasClass(tabName)) {
              var $tab = $tabbedOptions.find("a#"+tabName+"-carosel-link");
              var $tabCopy = $("div#"+tabName+"-intro-block-copy");
              var $tabCarosel = $("div#"+tabName+"-carosel");
            
              if($mainBlock.hasClass(tabName)) {
                $mainBlock.removeClass(tabName);
              }
            
              if($tabCopy.hasClass("selected")) {
                $tabCopy.removeClass("selected");
              }
              if($tabCarosel) {
                if($targetCarosel) {
                  if($tabCarosel.hasClass("active")) {
                    $tabCarosel.removeClass("active")
                  }
                }
              }
              if($tab.parent().hasClass("selected")) {
                $tab.parent().removeClass("selected");
              }
            }
          }
        }
      
        if($targetCarosel) {
          if(!$targetCarosel.hasClass("active")) {
            $targetCarosel.addClass("active");
            var targetId = section+"-carosel";
            if(animRefs[targetId]) {
              animRefs[targetId].gotoSlide(1,true);
            }
          }
        }
      
        if(!$targetCopy.hasClass("selected")) {
          $targetCopy.addClass("selected")
        }
      
        if(!$mainBlock.hasClass(section)) {
          $mainBlock.addClass(section);
        }
      
        if(!$(selfRef).parent().hasClass("selected")) {
          $(selfRef).parent().addClass("selected");
        }
      }
    
      $(selfRef).click(function() {
        swapContent(tabLink);
        return false;
      });
    });
  
  	$(introBlockRef).find("div#intro-block-media div.carosel-holder").each(function() {
  		/*** Parent container with overflow hidden ***/
    	var container = this;
		
  		/*** The ID for the carosel ***/
  		container.caroselID = $(container).attr("id");
		
  		/*** The controls holder to target during animation ***/
  		container.$controls = $(container).find('ul.carosel-nav');
		
  		/*** The actual carosel content holder ***/
  		container.$carosel = $(container).find('ul.carosel-content-list');
		
  		/*** The items in the carosel to transition between ***/
  		container.$mediaItems = container.$carosel.find('li');
		
  		/*** Get an entry to calculate dimensions ***/
  		container.$singleEntry = container.$mediaItems.filter(':first');
		
  		/*** How wide each media entry is (with the border) ***/
  		container.mediaEntryWidth = container.$singleEntry.outerWidth();
		
  		/*** How many are visible at any given time ***/
  		container.numberVisible = Math.ceil(($(container).innerWidth() / container.mediaEntryWidth));
		
  		/*** How many slides do we have to transition? ***/
  		container.slideCount = Math.ceil(container.$mediaItems.length / container.numberVisible);
		
  		/*** Start by showing the first slide ***/
  		container.currentSlide = 1;
		
  		/*** Variable to hold slideAnimation call ***/
  		container.slideAnimation;
		
  		/*** Variable to hold gotoSlide call ***/
  		container.gotoSlide;
		
  		/*** The timeout holder ***/
  		container.animationDelay;
		
  		container.checkRealPos = function(isStart) {
  			isStart = (typeof(isStart) == 'undefined')?false:true;
				 
  			var caroStartPos = container.$carosel.position();
  			var realPos = caroStartPos.left;
  			var expectedPos = Math.abs((-1 * container.currentSlide * container.mediaEntryWidth));

  			if(realPos != (-1 * expectedPos)) {
  				if(realPos != 0) {
  					if(isStart) {
  						realPos = realPos - container.mediaEntryWidth;
  					}
  					container.currentSlide = Math.round((Math.abs(realPos) / container.mediaEntryWidth));
  				} else {
  					if(isStart) {
  						container.currentSlide = 1;
  					} else {
  						container.currentSlide = 0;
  					}
  				}
  			}
			
  			//alert(currentSlide);
  		}
		
  		/*** We need to duplicate the content of the first and last slide content to make it seamless ***/
  		container.$mediaItems.filter(':first').before(container.$mediaItems.slice(-container.numberVisible).clone().each(function() {
  		  var firstMediaItem = this;
  		  
  			firstMediaItem.origID = $(firstMediaItem).attr("id");
  			firstMediaItem.numericID = firstMediaItem.origID.substring((firstMediaItem.origID.lastIndexOf("-") + 1), firstMediaItem.origID.length);
  			firstMediaItem.newID = container.caroselID+'-clone-entry-'+firstMediaItem.numericID;
  			firstMediaItem.newLinkID = container.caroselID+'-carosel-clone-entry-link-'+firstMediaItem.numericID;
			
  			$(firstMediaItem).find('a.linkover')
  				.attr('id', firstMediaItem.newLinkID);
			
  			$(firstMediaItem)
  				.attr('id', firstMediaItem.newID)
  				.addClass('cloned');
  		}));
  		container.$mediaItems.filter(':last').after(container.$mediaItems.slice(0, container.numberVisible).clone().each(function() {
  		  var lastMediaItem = this;
  		  
  			lastMediaItem.origID = $(lastMediaItem).attr("id");
  			lastMediaItem.numericID = lastMediaItem.origID.substring((lastMediaItem.origID.lastIndexOf("-") + 1), lastMediaItem.origID.length);
  			lastMediaItem.newID = container.caroselID+'-clone-entry-'+lastMediaItem.numericID;
  			lastMediaItem.newLinkID = container.caroselID+'-carosel-clone-entry-link-'+lastMediaItem.numericID;
			
  			$(lastMediaItem).find('a.linkover')
  				.attr('id', lastMediaItem.newLinkID);
				
  			$(lastMediaItem)
  				.attr('id', lastMediaItem.newID)
  				.addClass('cloned');
  		}));
		
  		/*** Deal with video links ***/
  		container.$mediaItems.each(function() {
  		  var mediaItem = this;
  		  
  			if($(mediaItem).hasClass("video")) {
  				mediaItem.$liID = $(mediaItem).attr("id");
				
  				mediaItem.$videoPlay;
				
  				$(mediaItem).find('a.linkover').each(function() {
  				  var thisLinkOver = this;
  				  
  					thisLinkOver.contId = $(thisLinkOver).attr("id");
  					thisLinkOver.video = $(thisLinkOver).attr("href");
					
  					thisLinkOver.$videoPlayerControls = $("<div class=\"video-player-controls-hold clearfix\" id=\""+mediaItem.$liID+"-pc\"></div>");
					
  					$(thisLinkOver).parent().append(thisLinkOver.$videoPlayerControls)
					
  					mediaItem.$videoPlay = $f(thisLinkOver.contId, {
  							src: "flash/flowplayer/flowplayer.commercial-3.2.1.swf",
  							wmode: "transparent"
  						},
  						{
  							clip: {
  								baseUrl: MIYOLib._conf.siteBaseURL
  							},
  							playlist: [
  								{
  									url: thisLinkOver.video,
  									autoPlay: true,
  									autoBuffering: true
  								}
  							],
  							key: '#$c453c610891d48fc785',
  							contextMenu: [ 
			
  									// 1. "About Flowplayer...";  selecting this item goes to our homepage 
  									{'About Wonder Associates ...' : function() { 
  											location.href = "http://www.wonderassociates.com"; 
  									}}, 
			
  									// 2. menu separator. 
  									'-', 
			
  									// 3. version information. 
  									'Wonder Media Player v3.1.5' 
  							],
  							plugins: {
  								controls: null
  							}
  						}
  					).controls(mediaItem.$liID+"-pc");
  				});
				
  				$(mediaItem).find('a.linkover').click(function() {
  				  var thisLinkOver = this;
  				  
  					clearTimeout(container.animationDelay);
  					$(thisLinkOver).parent().addClass("playing");
  					thisLinkOver.$videoPlayerControls = $(thisLinkOver).parent().find("div.video-player-controls-hold");
  					container.$controls.css("display", "none");
			
  					thisLinkOver.$closeButton = $("<a href=\"#\" class=\"close-button\"><span class=\"accessibility\">Close</span></a>");
  					thisLinkOver.$closeButton.click(function() {
  					  var thisCloseButton = this;
  					  
  						$(thisCloseButton).parent().removeClass("playing");
  						mediaItem.$videoPlay.unload();
  						thisLinkOver.$videoPlayerControls.remove();
  						$(thisCloseButton).remove();
  						container.$controls.css("display", "block");
  						if(container.slideCount > 1) {
  							container.animationDelay = setTimeout(container.slideAnimation, 5000);
  						}
  						return false;
  					});
			
  					$(thisLinkOver).parent().append(thisLinkOver.$closeButton);
  				});
  			}
  		});
		
  		/*** Refresh the $mediaItems list ***/
  		container.$mediaItems = container.$carosel.find('li');
		
  		/*** Calculate the new width of the carosel content holder ***/
  		container.newWidth = container.$mediaItems.length * container.mediaEntryWidth;
		
  		container.checkRealPos(true);
		
  		/*** Set new properties for the carosel content holder ***/
  		container.$carosel.css('width', container.newWidth);
  		container.$carosel.css('left', (-1 * container.currentSlide * container.mediaEntryWidth));
  		container.$controls.find("#"+container.caroselID+"-link-"+container.currentSlide).addClass("selected");
  		container.$mediaItems.find("#"+container.caroselID+"-entry-"+container.currentSlide).addClass("selected");
		
  		if(container.slideCount < 2) return;
		
  		container.gotoSlide = function(slideNo,navClick) {
  			navClick = (typeof(navClick) == 'undefined')?false:true;
			
  			/*** Get where we currently think we are ***/
  			var originalPos = container.currentSlide;
			
  			/*** Check where we REALLY are ***/
  			container.checkRealPos();
			
  			/*** If they are not equivalent correct values ***/
  			if(originalPos != container.currentSlide) {
  				container.$carosel.css('left', (-1 * container.currentSlide * container.mediaEntryWidth));
				
  				if(!navClick) {
  					if(container.currentSlide >= container.slideCount) {
  						slideNo = 2;
  					} else {
  						slideNo = container.currentSlide + 1;
  					}
  				}
  			}
			
  			/*** Used for setting "selected" class ***/
  			var actualSlide;
			
  			if(slideNo > container.slideCount) {
  				actualSlide = 1;
  			} else if(slideNo < 1) {
  				actualSlide = container.slideCount;
  			} else {
  				actualSlide = slideNo;
  			}
			
  			/*** Determine the direction of the transition ***/
  			var direction = slideNo < container.currentSlide ? -1 : 1;
			
  			/*** Get the required slide shift ***/
  			var slideShift = Math.abs(container.currentSlide - slideNo);
			
  			/*** How much in pixels we are shifting ***/
  			var leftShift = direction * container.mediaEntryWidth * container.numberVisible * slideShift;
			
  			/*** Remove any that are previously set as selected ***/
  			container.$controls.find("li.selected").removeClass("selected");
			
  			/*** Set the taget frame to selected ***/
  			container.$controls.find("li#"+container.caroselID+"-link-"+actualSlide).addClass("selected");
			
  			container.$carosel.find('li.selected').removeClass("selected");
			
  			container.$carosel.filter(':not(:animated)').animate({
  				left: '-='+leftShift
  			}, 500, function () {
  				if (slideNo == 0) {
  					container.$carosel.css('left', -(container.mediaEntryWidth * container.numberVisible * container.slideCount));
  					slideNo = container.slideCount;
  				} else if (slideNo > container.slideCount) {
  					container.$carosel.css('left', -(container.mediaEntryWidth * container.numberVisible));
  					slideNo = 1;
  				}
				
  				container.$carosel.find('li#'+container.caroselID+'-clone-entry-'+slideNo).addClass("selected");
  				container.$carosel.find('li#'+container.caroselID+'-entry-'+slideNo).addClass("selected");
		
  				container.currentSlide = slideNo;
  			}); 
			
  			container.currentSlide = slideNo;  
			
  			clearTimeout(container.animationDelay);
  			container.animationDelay = setTimeout(container.slideAnimation, 5000);            
			
  			return false;
  		}
		
  		container.slideAnimation = function() {
  			var jumpTo = container.currentSlide + 1;
			 
  			container.gotoSlide(jumpTo);
  		}
		
  		container.$controls.find("li > a").each(function() {
  		  var thisControlLink = this;
  		  
  			thisControlLink.origID = $(thisControlLink).parent().attr("id");
  			thisControlLink.numericID = Number(thisControlLink.origID.substring((thisControlLink.origID.lastIndexOf("-") + 1), thisControlLink.origID.length));
			
  			$(thisControlLink).click(function() {
  				container.gotoSlide(thisControlLink.numericID,true);
  				return false;
  			});
  		});
		
  		container.animationDelay = setTimeout(container.slideAnimation, 5000);
  		
  		var caroselIDString = container.caroselID;
  		animRefs[caroselIDString] = container;
  	});
	});
}

function initSubscribeSelectAll() {
  $("ul.subscribe-option-list").each(function() {
    var optionListInst = this;
    
    optionListInst.$triggerCheckbox = $("<input type=\"checkbox\" class=\"checkbox select-all\" title=\"Select all\" />");
    
    optionListInst.$selectAllLabel = $("<label>All of the above</label>");
    
    optionListInst.$selectAllFormRow = $("<li class=\"clearfix\"></li>");
    
    optionListInst.$selectAllFormRow.append(optionListInst.$triggerCheckbox);
    optionListInst.$selectAllFormRow.append(optionListInst.$selectAllLabel);
    
    $(optionListInst).append(optionListInst.$selectAllFormRow);
    
    optionListInst.$triggerCheckbox.click(function() {
  		var checkAll = $(this).attr("checked");

  		if(checkAll) {
  			$("input.checkbox", $(optionListInst)).not(".select-all").attr("checked", "checked");
  		} else {
  			$("input.checkbox", $(optionListInst)).not(".select-all").removeAttr("checked");
  		}
  	});

  	$("input.checkbox", $(optionListInst)).not(".select-all").click(function() {
  		var newTriggerStatus = true;

  		$("input.checkbox", $(optionListInst)).not(".select-all").each(function() {
  			if(!$(this).attr("checked")) {
  				newTriggerStatus = false;
  			}
  		});

  		if(newTriggerStatus) {
  			optionListInst.$triggerCheckbox.attr("checked", "checked");
  		} else {
  			optionListInst.$triggerCheckbox.removeAttr("checked");
  		}
  	});
  	
  	$("input.checkbox", $(optionListInst)).not(".select-all").each(function() {
  		var newTriggerStatus = true;

  		$("input.checkbox", $(optionListInst)).not(".select-all").each(function() {
  			if(!$(this).attr("checked")) {
  				newTriggerStatus = false;
  			}
  		});

  		if(newTriggerStatus) {
  			optionListInst.$triggerCheckbox.attr("checked", "checked");
  		} else {
  			optionListInst.$triggerCheckbox.removeAttr("checked");
  		}
  	});
  });
}
