﻿var SiteSettings =
{
    InStaticMode:false,
    Blog: { }, //populated upon pageload with pre-set settings from the db
    Theme: { current: { id: function() { var curCss = findDotNetObjectByIdAndTag('css1','link'); return (curCss.href.match(/dark/gi) ? '_d' : '_l'); } } },
    Form: { MaxTimeout: 15000, AjaxBasePath: Site.UrlPath },
    KillAjaxCalls : function() { GetObjAjax.Timer.Kill(); FormObjAjax.Timer.Kill(); BlogObjAjax.Kill(); }
}

var FormObjAjax =
{
    CurrentForm:'',
    IsReady:false, Active:false, ErrorThrown:false,
    SetActive:function(b) { this.Active=b; },
    Timer: { Load:false, ReLoad:function() { clearTimeout(this.Load); FormObjAjax.Active=false; this.Load=arguments[0]; },
             Kill: function() { FormObjAjax.Timer.ReLoad(null); FormObjAjax.ResetOutput(); } },
    InitTimeout:  function() { this.Timer.Load=setTimeout("throwFormSubmitError(1);",SiteSettings.Form.MaxTimeout); },
    StartClocking:function() { this.CurrentForm=arguments[0]; this.InitTimeout(); },
    ResetOutput:  function() { this.CurrentForm=''; this.FieldCollection=[]; this.AjaxParams=false; this.ErrorThrown=false; },
    FieldCollection:[],
    FieldErrorCollection:[],
    ObjectCollection:false,
    AjaxParams:false,
    UrlValidation: { Checking:false, UrlFound:false }, //not used, for now
    BasePath: SiteSettings.Form.AjaxBasePath
}
var GetObjAjax =
{
    Active:false, SetActive:function(b) { this.Active=b; },
    Timer: { Load:false, ReLoad:function() { clearTimeout(this.Load); GetObjAjax.Active=false; this.Load=arguments[0]; },
             Kill:function() { GetObjAjax.Timer.ReLoad(null); } },
    AjaxParams:false,
    BasePath: SiteSettings.Form.AjaxBasePath
}

var httpFormPost = HttpObj();
var httpGet      = HttpObj();

var BLOG_INVIEW_4_MOO = false;
var OmniCordion;

getRidOfGoogleToolbarHiJacking();

function initNavChange()
{
    SiteSettings.KillAjaxCalls();

    if (initNavChange.arguments.length > 0)
        OmniCordion.display(initNavChange.arguments[0]);
    else
    {
        // Clear out any initiated reply on the comment form
        hideBlogCommentsAndReply();
    }
    
    BLOG_INVIEW_4_MOO = false;
}

function toggleTheme(selectedTheme)
{
    var curStyleSheet = findDotNetObjectByIdAndTag('css1','link');
    var altStyleSheet_lite = findDotNetObjectByIdAndTag('css2','link');
    var altStyleSheet_dark = findDotNetObjectByIdAndTag('css3','link');
    var altStyleSheet, curTheme;
    
    if (curStyleSheet.href.match(/dark/gi))
    {
        altStyleSheet = altStyleSheet_lite.href;
        curTheme = 'dark';
    }
    else
    {
        altStyleSheet = altStyleSheet_dark.href;
        curTheme = 'lite';
    }
    
    if (selectedTheme != curTheme)
    {
        curStyleSheet.href = altStyleSheet;
        var AjaxParams = 'InjectionFree=true&AjaxAction=SaveTheme&Theme='+selectedTheme;
        
        doHttpGet(AjaxParams);
    }
}

/////////////////////////////////////////////////////////////
// COMMON FUNCTIONS
/////////////////////////////////////////////////////////////

function resetPageDynamics()
{
    // Kill any incoming/outgoing ajax calls
    FormObjAjax.Timer.Kill();
    GetObjAjax.Timer.Kill();
    
    // Reset form (*) error indicators.  We'll leave the data intact
    ResetLastErrorState();
    
    //> Resetting WORK dynamics
    
    if (LastSelection_Work)
        doOpacity(LastSelection_Work, 100, 0, 100, 'block');

    for (var obj in objWwdTitles)
    {
        if (obj != LastSelection_Work)
            forceOpacity(0, obj);

        docObj(obj+'_Link').className = 'link_deselected';
    }
    LastSelection_Work = false;
    
    // if you don't reset this object, ie will layer it over some career/conact info.  Normally this is
    // fine, but if any links are present, they will be un-reachable.
    docObj('wwd_descriptions').style.display = 'none';    
    
    //> Resetting CAREER dynamics

    if(docObj('divJobDDL'))
    {
        var JobDDLHeight = docObj('divJobDDL').style.height.replace(/px/g,'');
        doExpansion('divJobDDL', JobDDLHeight, 0, 50, 'height');
        DDLState.isOpen = false;
        showFileBrowser(false);
    }
}

function loadPageDynamics(id)
{
    var content_section = id.replace('nav_','');
    
    switch (content_section)
    {
        case 'omnitech': getNextFeedbackItem(); break;
        case     'work': LoadWhatWeDo('WWD_AppDevelopment_Link',true); break;
        case  'careers': showFileBrowser(true); break;
    }
    
    // switch the nav images to that which was selected
    // obselete: docObj('nav_header'+SiteSettings.Theme.current.id).className = content_section;
    docObj('nav_header').className = content_section;
    
    // this takes that annoying white border away from the selected image in firefox.
    // note: this will bust in ie
    if ('ie' != thisBrowser()) docObj('hdnFocusDecoy').focus();    
}

function initBlog()
{
    BlogObjAjax.IsReady = true;
    
    // when changing to the blog from the nav, we do not want to scroll into focus in order to
    // keep the asthetic slide up/down feel
    Blog.ScrollPageToFocus = false;

    if (BLOG_INVIEW_4_MOO)
    {
        // Blog already loaded, let's quick get them back to the default view
        BlogObjAjax.Post.CurrentView.Reset();
        
        // Clear out any initiated reply on the comment form
        hideBlogCommentsAndReply();
        
        BlogObjAjax.Post.Timer.ReLoad(setTimeout("doBlogPostMethod();",0));
        BlogObjAjax.Category.Timer.ReLoad(setTimeout("getBlogCategoryAll();",0));
        BlogObjAjax.RecentComments.Timer.ReLoad(setTimeout("getBlogRecentComments();",0));
    }
    else
    {
        BLOG_INVIEW_4_MOO = true;
        Blog.UseAccordianScroll = true;
        BlogObjAjax.Post.CurrentView.Reset();

        // Lets wait a second to let the static data slide up/down nicely.. then we'll silently update
        BlogObjAjax.Post.Timer.ReLoad(setTimeout("doBlogPostMethod();",750));
        BlogObjAjax.Category.Timer.ReLoad(setTimeout("getBlogCategoryAll();",500));
        BlogObjAjax.RecentComments.Timer.ReLoad(setTimeout("getBlogRecentComments();",1000));
        BlogObjAjax.Archive.SwapStaticLinks(docObj('Blog_Archives').getElementsByTagName('a'));
    }
}

function docObj(id)
{
    if (document.getElementById(id))
        return document.getElementById(id);
}

function findPos(obj) 
{
	var curleft = curtop = 0;
	if (obj.offsetParent)
	{
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent)
		{
			curleft += obj.offsetLeft
			curtop  += obj.offsetTop
		}
	}
	return { left:curleft, top:curtop };
}


function doOpacity(id, opacStart, opacEnd, millisec, block_style)
{
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--)
        {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
    else if(opacStart < opacEnd)
    {
        for(i = opacStart; i <= opacEnd; i++)
        {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
	
	docObj(id).style.display = block_style;
}

function changeOpac(opacity, id)
{
    var objStyle = docObj(id).style;
    objStyle.opacity = (opacity / 100);
    objStyle.MozOpacity = (opacity / 100);
    objStyle.KhtmlOpacity = (opacity / 100);
    objStyle.filter = "alpha(opacity=" + opacity + ")";
}
function forceOpacity(opacity, id)
{
    changeOpac(opacity, id)
}

function doExpansion(id, expStart, expEnd, millisec, attrib)
{
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the sizin', if start and end are the same nothing happens
    if(expStart > expEnd) {
        for(i = expStart; i >= expEnd; i--)
        {
            setTimeout("changeSize('" + attrib + "'," + i + ",'" + id + "'," + timer + ")",(timer * speed));
            timer++;
        }
    }
    else if(expStart < expEnd)
    {
        for(i = expStart; i <= expEnd; i++)
        {
            setTimeout("changeSize('" + attrib + "'," + i + ",'" + id + "'," + timer + ")",(timer * speed));
            timer++;
        }
    }
}

function changeSize(attrib, size, id, pass)
{
    if (attrib == 'height')
        docObj(id).style.height = size+'px';
    else
        docObj(id).style.width = size+'px';
        
    if (size <= 0 && pass > 0)
        docObj(id).style.display = 'none';
}

function txt2Html(txt)
{
    var html = txt;    
    html = html.replace(/\&quot\;/gi,'"');
    html = html.replace(/\&lt\;/gi,'<');
    html = html.replace(/\&gt\;/gi,'>');
    html = html.replace(/\&nbsp\;/gi,' ');
    return html;
}          

function writeMail(to,domain,isLink)
{
    var email = to + '@' + domain + '.com';
    
    if (isLink)
        email = '<a href="mailto:'+email+'">'+email+'</a>';
        
    document.write(email);
}

function findDotNetObjectByIdAndTag(id,tag)
{
    var arObj = document.getElementsByTagName(tag);
    var serverCtrlName = id.replace(/_/g,'$');
    var regExId = new RegExp(id+"$", "ig");

    for (var i = 0; i < arObj.length; i++)
    {
        if (arObj[i].id)
        {            
            if (arObj[i].id.match(regExId))
                return arObj[i];
        }
        else if (arObj[i].name)
        {
            (arObj[i].name == serverCtrlName)
                return arObj[i];
        }
    }
    
    return false;
}

function showFileBrowser(show)
{	
	var fBrowser = docObj('fileBrowser');
	if (fBrowser)
	    fBrowser.style.display = (show?'block':'none');
}

function addThisEvent(obj, evType, fn, useCapture)
{
	if (obj)
	{
		if(obj.addEventListener)
			obj.addEventListener(evType, fn, useCapture);
		else if(obj.attachEvent)
			obj.attachEvent('on'+evType, fn);
	}
}

function thisBrowser()
{
    if (navigator.appName == 'Microsoft Internet Explorer')
        return 'ie';
    else
        return true;
}

function httpResponseIsValid(http)
{
    var t;
    
    if (http.readyState == 4)
    {
        t = http.responseText.replace(/ /g,'');
        if (t.length != 0 && !t.match(/^\<html\>/i))
            return true;
        else
            return false;
    }
}

function HttpObj()
{
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined')
  {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}

function getRidOfGoogleToolbarHiJacking()
{
     addThisEvent(window, 'load', setListenerForGoogleToolbarHiJack, true)
}

function setListenerForGoogleToolbarHiJack()
{
    var arInput  = document.getElementsByTagName('input');
    var arSelect = document.getElementsByTagName('select');
    var arFlds = new Array(arInput, arSelect);

    if (arFlds.length)
    {
        for (var i = 0; i < arFlds.length; i++)
        {
            if (arFlds[i].length)
            {
                for (var n = 0; n < arFlds[i].length; n++)
                {
                    addThisEvent(arFlds[i][n], 'propertychange',revertGoogleToolbarStyle,true);
                    arFlds[i][n].style.backgroundColor = "";
                }
            }
        }
    }
}

function revertGoogleToolbarStyle()
{
    if (event.srcElement.style.backgroundColor != '') // != "#a0d0ff"
        event.srcElement.style.backgroundColor = '';
}

var pageDisplays;
var pageTogglers;    
function InitializePage()
{        
    pageDisplays = $$('div.pageDisplays');         
    pageTogglers = $$('li.togglers');
    pageDisplays.setStyles({'height': '0', 'overflow': 'hidden'});
    
    try
    {
        CreateListItems();
        DisplaysInit();
    }
    catch(e)
    {
        //alert(e);
    }   
}    

function DisplaysInit()
{  
	//initialization of togglers effects		
	pageTogglers.each(function(toggler, i)
	{			
		toggler.$tmp.first = toggler.getFirst();
		toggler.$tmp.fx = new Fx.Style(toggler, 'background-color',
		                                {'wait': false, 'transition':Fx.Transitions.Circ.easeInOut }); //Quart.easeOut;
	});		
	
	OmniCordion = new Accordion(pageTogglers, pageDisplays, 
	{	   
	       'opacity': false,			
		     'start': false,			
		'transition': Fx.Transitions.Quad.easeOut,
	    
		    onActive: function(toggler) { resetPageDynamics(); loadPageDynamics(toggler.id); },		
		onBackground: function(toggler) { toggler.$tmp.fx.stop(); }//toggler.setStyle('background-color', toggler.color).$tmp.first.setStyle('color', '#222');
	});

	var urlParam = window.location.href;
	if (urlParam.match(/\#[0-9]$/))
	{
	    var i = urlParam.split(/#/);
	        i = i[i.length-1];
	    OmniCordion.display(i); //came from the static portion of the site, load the correct pane.
	    
	    //if you don't force applicable ajax calls, the static controls (or lacktherof) will load
	    if (i==2) initBlog();
	}
	else
	    OmniCordion.display(0); //open omnitech home pane by default	
}