﻿var itemCounter = 0;

$(document).ready(function () {

  if ($(".BlogPager").length != 0) {
    var PreviousButton;
    if ($(".SelectedPrev").length != 0) PreviousButton = $(".SelectedPrev");
    if ($(".UnselectedPrev").length != 0) PreviousButton = $(".UnselectedPrev");
    PreviousButton.addClass('PagerButton');
    PreviousButton.addClass('PreviousPagerButton');
    PreviousButton.html('Newer Posts');
    var NextButton;
    if ($(".SelectedNext").length != 0) NextButton = $(".SelectedNext");
    if ($(".UnselectedNext").length != 0) NextButton = $(".UnselectedNext");
    NextButton.addClass('PagerButton');
    NextButton.addClass('NextPagerButton');
    NextButton.html('Older Posts');
  };


  var BrowserVersion = String(BrowserDetect.version);
  var thisBrowserVersion = BrowserVersion.replace(".", "");
  $('body').addClass(BrowserDetect.browser + '' + thisBrowserVersion);

  // Update navigation links for styling purposes, then switching visibility to avoid a flash of unstyled content
  $(".IE8 #MainNavigation li a, .IE7 #MainNavigation li a, .IE6 #MainNavigation li a, .IE8 #SectionNavigation li a, .IE7 #SectionNavigation li a, .IE6 #SectionNavigation li a").wrapInner('<span />');
  $(".IE8 #MainNavigation, .IE7 #MainNavigation, .IE6 #MainNavigation, .IE8 #SectionNavigation, .IE7 #SectionNavigation, .IE6 #SectionNavigation").css('visibility', 'visible');

  // Animated background hovers
  var argAllowAnimateBkg = false;
  if (!$.browser.msie) {
    argAllowAnimateBkg = true;
  } else {
    if ($.browser.version > 7) argAllowAnimateBkg = true;
  }

  //Smooth scrolling of local links
  $.localScroll();

  //Create accordions
  $(".Accordion").accordion({
    autoHeight: false,
    navigation: true,
    collapsible: true,
    clearStyle: true,
    icons: { 'header': 'ui-icon-down', 'headerSelected': 'ui-icon-up' },
    active: 'none'
  });

  //Create homepage carousel
  if ($("#ServicesCarousel").length != 0) {
    $("#ServicesCarousel").carousel({
      itemsPerTransition: 1,
      orientation: 'horizontal',
      noOfRows: 1,
      pagination: false,
      nextPrevActions: true,
      autoScroll: true,
      pause: 8000,
      continuous: true
    });
  }

  //Create case study carousel
  if ($("#CaseStudyCarousel").length != 0) {
    $("#CaseStudyCarousel").carousel({
      itemsPerTransition: 1,
      orientation: 'horizontal',
      noOfRows: 1,
      pagination: true,
      insertPagination: function () {
        $(this).appendTo('.CaseStudyRibbon');
      },
      nextPrevActions: false,
      autoScroll: true,
      pause: 8000,
      continuous: true,
      startAt: 0,
	  afterAnimate: function() { 
		updateCarouselTitle();
	  }
    });
    $("#CaseStudyCarousel .btn_next").click(function () {
      $("#CaseStudyCarousel").carousel('next');
    });
  }

  if ($(".InlineVideo").length > 0) {
    $(".InlineVideo").each(function () {
      itemCounter++;
      var strID = "InlineVideo" + itemCounter;
      $(this).wrapInner('<div id="' + strID + '" />');
      var objID = $("#" + strID);
      var strSRC = $("a", objID).attr('href');
      var strVideoType = 'local';
      if (strSRC.search(/stream100/i) != 0) strVideoType = 'streaming';

      if (strVideoType == 'local') { //Local video
        if (strSRC.substring(0, 3) != 'http') strSRC = 'http://' + document.domain + strSRC;
        var strSkin = 'http://dev.datausa.com/scripts/PortfolioSkin.xml';
        var strPoster = $("img", objID).attr('src');
        var videoAttributes = { allowFullScreen: 'true', id: strID, name: 'StrobeMediaPlayback', allowScriptAccess: 'always', type: 'application/x-shockwave-flash' };
        var videoFlashVars = { src: strSRC, skin: strSkin, poster: strPoster, streamType: 'recorded', autoRewind: 'true', controlBarAutoHideTimeout: '1' };
        var videoParams = { allowFullScreen: 'true', wmode: 'transparent' };
        swfobject.embedSWF('/media/StrobeMediaPlayback.swf', strID, '383', '320', '10.0.0', '/media/flash/expressInstall.swf', videoFlashVars, videoParams, videoAttributes);
      } else if (strVideoType == 'streaming') { //Streaming video
        $("a", objID).replaceWith('<iframe class="dataplayer" type="text/html" width="640" height="360" src="' + strSRC + '" frameborder="0"></iframe>');
      }
    });
  };
  
  if($(".ContentModal").length > 0) {
	var modalId = $("#" + $(".ContentModal").attr('data-target'));
	var modalTitle = $(".ContentModal").attr('data-title');
	modalId.dialog({
		title: modalTitle,
		autoOpen: false,
		modal: true,
		draggable: false,
		height: 412,
		width: 670
	});

	$(".ContentModal").click(function () {
		modalId.dialog("open");
		return false;
	});
	$(".ui-widget-overlay").live("click", function () {
		modalId.dialog("close");
	});
  }

  if ($(".ModalVideo").length > 0) {
    $(".ModalVideo").each(function () {
      itemCounter++;
      var strID = "ModalVideo" + itemCounter;
      $("form").append('<div id="' + strID + '" />');
      var objID = $("#" + strID);
      var strSRC = $(this).attr('href');
      $(this).attr('href', '#');
      var strVideoType = 'local';
      if (strSRC.search(/stream100/i) != 0) strVideoType = 'streaming';

      if (strVideoType == 'local') { //Local video
        if (strSRC.substring(0, 3) != 'http') strSRC = 'http://' + document.domain + strSRC;
        var strSkin = 'http://dev.datausa.com/scripts/PortfolioSkin.xml';
        var strPoster = $("img", objID).attr('src');
        var videoAttributes = { allowFullScreen: 'true', id: strID, name: 'StrobeMediaPlayback', allowScriptAccess: 'always', type: 'application/x-shockwave-flash' };
        var videoFlashVars = { src: strSRC, skin: strSkin, poster: strPoster, streamType: 'recorded', autoRewind: 'true', controlBarAutoHideTimeout: '1' };
        var videoParams = { allowFullScreen: 'true', wmode: 'transparent' };
        swfobject.embedSWF('/media/StrobeMediaPlayback.swf', strID, '383', '320', '10.0.0', '/media/flash/expressInstall.swf', videoFlashVars, videoParams, videoAttributes);
      } else if (strVideoType == 'streaming') { //Streaming video
        $(objID).html('<iframe class="dataplayer" type="text/html" width="640" height="360" src="' + strSRC + '" frameborder="0"></iframe>');
      }
      // Feedback Form
      objID.dialog({
        title: '',
        autoOpen: false,
        modal: true,
        draggable: false,
        height: 412,
        width: 670,
        beforeClose: function () {
          var detachedDATAPlayer = $(".dataplayer", objID).detach();
          detachedDATAPlayer.appendTo(objID);
        }
      });

      $(this).click(function () {
        objID.dialog("open");
        return false;
      });
      $(".ui-widget-overlay").live("click", function () {
        objID.dialog("close");
      });

    });
  };
  
  if ($("#HomepageBanner .BannerContent").length != 0){
	var banner = $("#HomepageBanner .BannerContent");
	var originalX = banner.position().left;
	var originalY = banner.position().top;
	var bannerHeight = banner.outerHeight();
	var newY = banner.parent().outerHeight();
//	alert('originalX = ' + originalX + '\n' +'originalY = ' + originalY + '\n' +'bannerHeight = ' + bannerHeight + '\n' +'newY = ' + newY + '\n');
	banner.css({ left: originalX, top: newY, visibility: 'visible'}).delay(100).animate({ top: originalY }, 500 );
  }

  if ($("#PortfolioBuckets").length > 0) {
    $("#PortfolioBuckets .Even").wrapAll('<div class="BucketsColumn BucketsColumnEven"></div>');
    $("#PortfolioBuckets .Odd").wrapAll('<div class="BucketsColumn BucketsColumnOdd"></div>');
    $("#PortfolioBuckets .Bucket").fadeIn('slow');
  };

  if ($("#ContactUsBuckets").length > 0) {
    $("#ContactUsBuckets .Bucket").fadeIn('slow');
  };

  TextBoxSwitch($("#SiteSearch input.SearchText"), "Search");
  var searchtextQuery = getParameterByName("searchtext");
  if (searchtextQuery.length > 0)
      $("#SiteSearch input.SearchText").val(searchtextQuery);

  if ($("#ContactForm").length > 0) {
    TextBoxSwitch($("#ContactName input"), "Name (required)");
    TextBoxSwitch($("#ContactEmail input"), "Email (required)");
    TextBoxSwitch($("#ContactPhone input"), "Phone");
    TextBoxSwitch($("#ContactQuestionComment textarea"), "Questions & Comments");
  };

  if ($(".CommentForm").length > 0) {
    TextBoxSwitch($("#plc_lt_zoneContent_Content_Content_lt_zoneContentBody_CommentView_commentView_ctrlCommentEdit_pnlName input"), "Name (required)");
    TextBoxSwitch($("#plc_lt_zoneContent_Content_Content_lt_zoneContentBody_CommentView_commentView_ctrlCommentEdit_pnlEmail input"), "Email (required)");
    TextBoxSwitch($("#plc_lt_zoneContent_Content_Content_lt_zoneContentBody_CommentView_commentView_ctrlCommentEdit_pnlUrl input"), "URL");
    TextBoxSwitch($("#plc_lt_zoneContent_Content_Content_lt_zoneContentBody_CommentView_commentView_ctrlCommentEdit_txtComments"), "Comment");
  };

  if (argAllowAnimateBkg == true) {
    if (!$.browser.msie) {
      BackgroundColorFade('#SiteMap a', '#848484', '#333333');
      BackgroundColorFade('#SiteMap li ul li a', '#B4B4B4', '#848484');
      BackgroundColorFade('#MainNavigation li a', '#333333', '#848484');
    } else {
      if ($.browser.version > 8) {
        BackgroundColorFade('#SiteMap a', '#848484', '#333333');
        BackgroundColorFade('#SiteMap li ul li a', '#B4B4B4', '#848484');
        BackgroundColorFade('#MainNavigation li a', '#333333', '#848484');
      };
    };
    BackgroundColorFade('p.SocialMedia a', '#B4B4B4', '#848484');
    BackgroundColorFade('.FeedLink', '#848484', '#333333');
    BackgroundColorFade('#SectionNavigation a', '#848484', '#333333');
    BackgroundColorFade('a.DateLozenge', '#e6ead8', '#faffea');
    BackgroundColorFade('.BannerContent .Lozenge', '#ddf7fe', '#eef9fc');
    BackgroundColorFade('#ContactSubmit input', '#848484', '#333333');
    BackgroundColorFade('.CommentForm td div input.SubmitButton', '#848484', '#333333');
  }
  // End animated background hovers


  // Portfolio Dropdown
  if ($("#PortfolioCategories").length > 0)  {
	  $("#PortfolioCategories").val(window.location.pathname);
	  $("#PortfolioCategories").dropkick({
		change: function (value, label) {
		  window.location.href = value;
		}
	  });
  }

  // Portfolio Section Title
  if ($("#SectionTitle").length > 0)  {
	var portfolioTitle = $("#SectionTitle").html();
    if (portfolioTitle.substr(0, 9) == "Portfolio" && portfolioTitle.length > 9) $("#SectionTitle").html(portfolioTitle.replace("Portfolio", "Portfolio > "));
  }

  if ($.browser.msie & $.browser.version < 7) {
    if ($("#HomepageBanner").length != 0) {
      var originalHtml = $("#HomepageBanner").html();
      $("#HomepageBanner").html('<div class="IEHomepageBannerContainer">' + originalHtml + '</div>');
    }
  }

});


function BackgroundColorFade(thisObject, originalColor, newColor) {
  if ($(thisObject).length != 0) {
    $(thisObject).animate({ backgroundColor: originalColor }, 0);
    $(thisObject).hover(function () {
      $(this).stop().animate({ backgroundColor: newColor }, 500);
    }, function () {
      $(this).stop().animate({ backgroundColor: originalColor }, 300);
    });
  }
}

function TextBoxSwitch(thisObject, defaultText) {
  // Search text box value switching
  var fieldTextBox = thisObject;
  var fieldTextBoxDefault = defaultText;
  fieldTextBox.val(fieldTextBoxDefault);
  fieldTextBox.focus(function () {
    if (fieldTextBox.attr('value') == fieldTextBoxDefault) {
      fieldTextBox.attr('value', '').removeClass('Edited');
    } else {
      fieldTextBox.addClass('Edited');
    };
  });
  fieldTextBox.blur(function () {
    if (fieldTextBox.attr('value') == '') {
      fieldTextBox.attr('value', fieldTextBoxDefault).removeClass('Edited');
    } else {
      fieldTextBox.addClass('Edited');
    };
  });
}

function updateCarouselTitle(){
	var currentPage = $("#CaseStudyCarousel").carousel('getPage');
	var currentSlide = '.rs-carousel-item-' + (currentPage - 1);
	var currentTitle = $(currentSlide).attr('title');

	$(".CarouselCaption").html(currentTitle);
};

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}
