function ajaxGoTo(href)
{
    //check if href is current
    var selected = $("a.selected:last").attr('onclick').toString();
    var start = selected.indexOf("ajaxGoTo(")+10;
    var sngle = selected.indexOf('")');
    var dble = selected.indexOf("')");
    var end;
    if (sngle > -1)
    {
        end = sngle;
    }
    else
    {
        end = dble;
    }
    var length = end - start;
    var curHref = selected.substr(start,length);
    if (curHref != href)
    {    
        loading(true);
            $.ajax({
              url: href,
              cache: false,
              dataType: "html",
              success: function(html){
                $("div#mainContent").html(html);
                animateContent(href);
                }
            });
     }
}

function forceAjaxGoTo(href)
{
 loading(true);
            $.ajax({
              url: href,
              cache: false,
              dataType: "html",
              success: function(html){
                $("div#mainContent").html(html);
                animateContent(href);
                }
            });
}

var pageTitles =
{
'portfolio' : 'portfolio*',
'clients' : 'clients*',
'comingSoon' : 'coming soon*',
'whoWeAre' : 'who we are*',
'services' : 'services*',
'contactUs' : 'contact us*',
'enquiry' : 'enquiry*',
'requestQuote' : 'request a quote*',
'briefUs' : 'brief us*'
}

function setTitle(title)
{
    document.title = currentSite + '* - ' + title;
}

function animateContent(href)
{
    collapseContainer();
    if (href == '/clients.aspx')
    {
        setTitle(pageTitles.clients);
        setTimeout('animateClients()',1000);
    }
    if (href == '/coming-soon.aspx')
    {
        setTitle(pageTitles.comingSoon);
        loading(false);
    }
    if (href == '/portfoliojs/portfolio.aspx')
    {
          setTitle(pageTitles.portfolio);
           $.ajax({
          url: '/portfoliojs.aspx',
          cache: false,
          dataType: "script",
          success: function(html){
                $.getScript('/scripts/portfolio.js');
                setTimeout('animatePortfolio()',3000);
            }
        });
    }
    if (href == '/services.aspx' || href == '/countonline-services.aspx')
    {
        setTitle(pageTitles.services);
        animateServices();
    }
    if (href == '/who-we-are.aspx' || href == '/countonline-who-we-are.aspx')
    {
        setTitle(pageTitles.whoWeAre);
//        if ($.browser.safari)
//        {
//            $('div#whoweareCliffnote').css('top','150px');
//        }
        loading(false);
    }
    if (href == '/contact.aspx?response='+currentSite || href == '/requestquote.aspx?response='+currentSite || href == '/clientbriefsheet.aspx?response='+currentSite)
    {
        setTimeout('animateForms()',100);
    }
    if (href == '/clientbriefsheet.aspx?response='+currentSite)
    {
        setTitle(pageTitles.briefUs);
        setTimeout('animateBrief()',600);
        setTimeout('checkForMore()',4000);
    }
    if (href == '/requestquote.aspx?response='+currentSite)
    {
        setTitle(pageTitles.requestQuote);
        setTimeout('animateRequest()',100);
    }
    if (href == '/contact-landing.aspx' || href == '/countonline-contact-landing.aspx')
    {
        setTitle(pageTitles.contactUs);
        animateContactLanding();
    }
    if (href == '/contact.aspx?response='+currentSite)
    {
        setTitle(pageTitles.enquiry);
        setTimeout('animateContact()',100);
    }
}

function loading(isLoading)
{
    if (isLoading)
    {
        $("div#mainContent").animate({"opacity": "0"}, 100); 
        $("div#loader").fadeIn(100);
    }
    else
    {
        $("div#loader").fadeOut("slow");
        $("div#mainContent").animate({"opacity": "1"}, 100); 
    }
}

function changeIframe(href)
{
$("div#mainContent iframe").attr('src',href);
}

function hideAllSubMenus()
{
hideContactSubMenu();
hideServicesSubMenu();
}
function  hideContactSubMenu()
{
	$("div#contact_submenu").hide("slow");
}
function hideServicesSubMenu()
{
    $("div#services_submenu").hide("slow");
}

function checkIfCurrentOrParent(jqObj,current)
{
    if (jqObj.attr("id").indexOf(current) == -1 && jqObj.parent().attr("id").indexOf(current) == -1)
    {
    return true;
    }
    else  return false;
}

$.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}

$(document).ready(function()
{
    if (currentSite == "counton")
    {
        $.preloadImages("images/enter_hover.gif","images/clients_selected_hover.gif","images/clients_hover.gif","images/portfolio_selected_hover.gif","images/portfolio_hover.gif","images/services_hover.gif","images/whoweare_hover.gif","images/contact_hover.gif","images/contact_selected_hover.gif","images/enquiry_hover.gif","images/requestquote_hover.gif","images/brief_hover.gif","images/trans.png");
    }
    else
    {
        $.preloadImages("images/counton/enter_hover.gif","images/counton/clients_selected_hover.gif","images/counton/clients_hover.gif","images/counton/portfolio_selected_hover.gif","images/counton/portfolio_hover.gif","images/counton/services_hover.gif","images/counton/whoweare_hover.gif","images/counton/contact_hover.gif","images/counton/contact_selected_hover.gif","images/counton/enquiry_hover.gif","images/counton/requestquote_hover.gif","images/counton/brief_hover.gif");
    }
posMiddle();
//posContent();
//find and remove blank paragraphes

//bind links
$("div.nav a[href=#]").bind("mouseover", function() {
$(this).attr("id",$(this).attr("id")+"_hover");
});

$("div.nav a[href=#]").bind("mouseout", function() {
var id= $(this).attr("id");
id = id.substr(0,id.lastIndexOf('_'));
$(this).attr("id",id);
});

//bind links
$("div.nav a[href=#]").bind("click", function() {
    //set all selected to not selected and not hover
    var clickedParentId = $(this).parent().attr("id").substr(0,4);
    $("div.nav a[id*=selected]").each(function() {
        var id= $(this).attr("id");
        //if the first 4 letters of this id and the clicked elements parent id are the same dont set this to not selected
        if ($(this).attr("id").substr(0,4) != clickedParentId)
        {
            id = id.substr(0,id.indexOf('_selected'));
            $(this).attr("id",id);
            $(this).removeClass("selected");
        }
    });
    //remove this hover 
    var id= $(this).attr("id");
    if (id.indexOf('_') != -1)
    {
        id = id.substr(0,id.lastIndexOf('_'));
        $(this).attr("id",id);
    }
    // add selected and hover
    $(this).attr("id",$(this).attr("id")+"_selected_hover");
    $(this).addClass("selected");


    if (checkIfCurrentOrParent($(this),"contact")) 
    {
    hideContactSubMenu();
    }
    if (checkIfCurrentOrParent($(this),"services"))
    {
    hideServicesSubMenu();
    }
});


//hide the submenus
$("div#contact_submenu").hide();
$("div#services_submenu").hide();
//bind contact click to show contactdiv
$("a[id*=contact]").bind("click",function() {
    $("div#contact_submenu").show("slow");
});
//bind services click to show servicesdiv
$("a[id*=services]").bind("click",function() {
    $("div#services_submenu").show("slow");
});


//text holders - using imagegen
var fontColour ;
if (document.location.toString().indexOf("countonline") > -1)
{
    fontColour = "f78f1e";
}
else
{
    fontColour = "e20177";
}
$("span[id^=img]").each(function () {
    var text = $(this).html();
    var parent = $(this).parent();
    parent.children("span[id^=img]").remove();
    parent.prepend('<img src="/umbraco/ImageGen.ashx?font=Helvitica%20Neueu&fontsize=19pt&fontcolor='+fontColour+'&fontstyle=bold&text='+text+'"></img>');
});

if (String(document.location).indexOf('a=succ') > 0)
{
    $("head").append('<script type="text/javascript">alert("Your request was successfully sent!");</script>');
}
else if (String(document.location).indexOf('a=fail') > 0)
{
    $("head").append('<script type="text/javascript">alert("Your request failed to send.");</script>');
}

});


var api = null;
function next()
{
    if (api == null)
    {
        var api = $("div.scrollables").scrollable({size:1,navi:'ul.tabs'});
    }
    api.next();
}
function prev()
{
    if (api == null)
    {
        var api = $("div.scrollables").scrollable({size:1,navi:'ul.tabs'});
    }
    api.prev();
}

//portfolio
function animatePortfolio()
{
    portfolioLoad();
    $("div[id^=col_]").bind("mouseenter", function () {
        $(this).append('<div style="height:100%;width:100%;background-color:transparent; background-image:url(/images/trans.png);position:relative;top:0px;" id="overlay"></div>');
    });
    
    $("div[id^=col_]").bind("mouseleave", function () {
        $(this).children("div#overlay").remove();
    });
     $("div[id^=col_portfolio_]").each(function () {
            var id = $(this).attr("url").substr($(this).attr("url").indexOf('item')+4, Math.abs($(this).attr("url").indexOf('item')+4 - $(this).attr("url").indexOf('.url')));
            if (eval("typeof(portfolioFolio.item"+id+")") != "undefined")
            {
                $(this).css("background-image","url('"+ eval("portfolioFolio.item"+id+".imgUrl")+"')");
            }
     });
     if (currentSite != 'counton')
	{
	  $('.col_4').css('background-color','#f7ae5f');
	}
	{
	  $('.col_4').css('background-color','#e26daa');
	}
     $('div.items').live('click',function () { $('img[alt=close x]').click() });
     loading(false);
}
function animateClients()
{
    if (clientsStyle)
    {
        $('head').append('<style type="text/css">'+clientsStyle+'</style>');
    }
  // alert($("div[id^=col_clients_]").length);
   // alert($("div[id^=col_clients_]").length);
     $("div[id^=col_clients_]").not("div.overlay").each(function () {
            if(Number($(this).attr("num")) < 29)
            {
                $(this).attr("id",eval("clientsCol.item"+$(this).attr("num")+".imgName"));
            }
     });
      $("div[id^=col_clients_]").each(function () {
            if(Number($(this).attr("num")) < 29)
            {
                var id = eval("clientsCol.item"+$(this).attr("num")+".imgName")+"_hover";
                $(this).attr("id",id);
            }
     });
        
        //bind links
        setTimeout(function () {
            if ($.browser.msie)
            {
                $.getScript('/scripts/jquery.hoverIntent.minified.js',function () {
                var config = {    
                 sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)    
                 interval: 25, // number = milliseconds for onMouseOver polling interval    
                 over:  function () 
                { 
                    $(this).children("div.overlay").show().fadeTo(400,1);
                },    
                 timeout: 500, // number = milliseconds delay before onMouseOut    
                 out:  function () 
                {
                    $(this).children("div.overlay").fadeTo(800,0.4).hide();
                }
                };
                $.getScript('/scripts/jquery.hoverIntent.minified.js');
                $("div.logo").hoverIntent(config)
                });
            }
            else 
            {
                $.getScript('/scripts/jquery.hoverIntent.minified.js',function () {
                var config = {    
                     sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)    
                     interval: 25, // number = milliseconds for onMouseOver polling interval    
                     over: function () 
                { 
                   $(this).children("div.overlay").fadeIn(300);
                },  
                
                     timeout: 500, // number = milliseconds delay before onMouseOut    
                     out:  function () 
                {
                    $(this).children("div.overlay").fadeOut(300);
                }
                };
                $("div.logo").hoverIntent(config);});
            }
        },1000);
    //next and prev buttons
    $('.nav').hover(function () { $(this).addClass('hover')},function () { $(this).removeClass('hover')});
      //scrollable 
    $.getScript('/scripts/jquery.scrollable-1.0.2.min.js', function () { setTimeout('$("div.scrollables").scrollable({size:1})',1000)});   
    loading(false);
    
}
var move = false;
var intervalHolder;
function calculateChildrensHeight(jObj)
{
    var height = 0;
    jObj.children().each(function () {
        height += $(this).height();
    });
    //alert(height);
    return height;
}

function expandContainer()
{
    $('div#mainContent').css({'overflow':'visible','z-index':'100','margin-top':'0px','height':'503px'});
}
function collapseContainer()
{
    $('div#mainContent').css({'overflow':'hidden','z-index':'1000','margin-top':'200px','height':'303px'});
}
function animateContactLanding()
{
    removeSpaces();
    $.getScript('/scripts/jquery.mousewheel.min.js', function () 
    {   
        $('div#innerPageContent').mousewheel(function (event,delta) 
                {   if (delta > 0)
                    {
                        serviceScrollSpeed('+',50);
                    }
                    else
                    {
                        serviceScrollSpeed('-',50);
                    }
//                  vel = Math.abs(delta);
//                  $(this).text(dir + ' at a velocity of ' + vel);
                    return false;   
                })
    });
    scrollHeight = 0;
    $('.contact-nav').hover(function () { $(this).addClass('hover')},function () { $(this).removeClass('hover')});
    //$("div#cliffnote").css('left','374px');
    //$("div#cliffnoteAsterix").css('left','370px');
    expandContainer();
        $('#scrollButtons .prev').bind("mousedown",function () {
            //alert('clicked');
            move = true;
            intervalHolder = setInterval('serviceScroll("+")',2);
        });
         $('#scrollButtons .next').bind("mousedown",function () {
            //alert('clicked');
            move = true;
            intervalHolder = setInterval('serviceScroll("-")',2);
        });
        $('#scrollButtons .prev,#scrollButtons .next').bind("mouseup",function () {
        //alert($('div#innerPageContent').height()+ $('div#innerPageContent').offset().top);
        move = false;
        clearInterval(intervalHolder);
        });
         $('#scrollButtons .prev,#scrollButtons .next').bind("mouseleave",function () {
        
        move = false;
        clearInterval(intervalHolder);
        });
        loading(false);
}
function animateServices()
{
    removeSpaces();
    if (servicesStyles)
    {
        $('head').append('<style type="text/css">'+servicesStyles+'</style>');
    }
    $.getScript('/scripts/jquery.mousewheel.min.js', function () 
    {   
        $('div#innerPageContent').mousewheel(function (event,delta) 
                {   if (delta > 0)
                    {
                        serviceScrollSpeed('+',50);
                    }
                    else
                    {
                        serviceScrollSpeed('-',50);
                    }
//                  vel = Math.abs(delta);
//                  $(this).text(dir + ' at a velocity of ' + vel);
                    return false;   
                })
    });
    scrollHeight = 0;
    $('.contact-nav').hover(function () { $(this).addClass('hover')},function () { $(this).removeClass('hover')});
    expandContainer();
    $('#scrollButtons .prev').bind("mousedown",function () {
        //alert('clicked');
        move = true;
        intervalHolder = setInterval('serviceScroll("+")',2);
    });
     $('#scrollButtons .next').bind("mousedown",function () {
        //alert('clicked');
        move = true;
        intervalHolder = setInterval('serviceScroll("-")',2);
    });
    $('#scrollButtons .prev,#scrollButtons .next').bind("mouseup",function () {
    //alert($('div#innerPageContent').height()+ $('div#innerPageContent').offset().top);
    move = false;
    clearInterval(intervalHolder);
    });
     $('#scrollButtons .prev,#scrollButtons .next').bind("mouseleave",function () {
    
    move = false;
    clearInterval(intervalHolder);
    });
    loading(false);
}
var currentSite =  document.location.toString().indexOf("countonline") > -1 ? 'countonline' : 'counton';
function removeSpaces() 
{
    if ($('div#mainContent p:first').html().length == 1 )
    {
        $('div#mainContent p:first').remove();
    }
}
function animateForms()
{
    var fontColour ;
    if (document.location.toString().indexOf("countonline") > -1)
    {
        fontColour = "f78f1e";
    }
    else
    {
        fontColour = "e20177";
    }
    $("span[id^=img]").each(function () {
        var text = $(this).html();
        var parent = $(this).parent();
        parent.children("span[id^=img]").remove();
        parent.prepend('<img src="/umbraco/ImageGen.ashx?font=Helvitica%20Neueu&fontsize=19pt&fontcolor='+fontColour+'&fontstyle=bold&text='+text+'"></img>');
    });
}
function animateBrief()
{
 currentStep = 1;
//create tabindexes 
var index = 0;
$('div#mainContent input').each(function () {
    index++;
    $(this).attr('tabindex',index);
});

 if ($.browser.msie)
 {
//    $("head").append('<style type="text/css">.step { height:40px; }</style>');
    //$("div#brief_spacer_imagery").css('height','62px');
    $("div#brief_style").css('height','60px');
   // $("img[src*=copy/]").parent().parent().css('height','24px');
   // $("div#brief_spacer_upload").remove();
   // $("div#brief_spacer_upload").remove();
   // $("div#brief_11").css('height','50px');
   $("div#brief_target_audience").css('height','30px');
 }
 else
 {
    $("div#brief_target_audience").css('height','40px');
 }
//space checkboxes
$("table[id$=rbCopy] td:first").css({'width':'102px'});
//upload expansion
$("div#addUpload").bind("click",function ()
{   
    if ($("tr.potentialFileUpload:first").length > 0)
    {
    $("tr.potentialFileUpload:first").removeClass("potentialFileUpload");
    var rowspan = $("div#addUpload").parent().attr("rowspan");
    $("div#addUpload").parent().attr("rowspan",rowspan+1).css("vertical-align","bottom");
    }
    else
    {
        $("div#addUpload").hide();
    }
});
//reference
$("table[id$=cblReference]+div.label+div").hide();
$("table[id$=cblReference]+div.label").hide() ;
$("input[type=checkbox][id$=cblReference_2]").bind("click",function() {
     $("table[id$=cblReference]+div.label+div").toggle();
     $("table[id$=cblReference]+div.label").toggle() ;
     //$("input[type=text][id$=txtOtherReference]").toggle("fast") ;
});
//imagery
$("input[type=text][id$=txtImagery]").hide();
$("input[type=radio][id$=rbOther],input[type=radio][id$=rbStockBudget]").bind("click",function() {
    $("input[type=text][id$=txtImagery]").show() ;
});
$("input[type=radio][id$=rbSupplied],input[type=radio][id$=rbPhotoshoot]").bind("click",function() {
    $("input[type=text][id$=txtImagery]").hide() ;
});

//project description
$("input[type=text][id$=txtOtherProject]").hide();
$("input[type=checkbox][id$=cblProjectDescription_4]").bind("click",function() {
 $("input[type=text][id$=txtOtherProject]").toggle("fast") ;
});
//bind next step
$(nextButton).bind("click",function ()
{
//get visible
for (var i=0;i<fieldMovementsPerStep;i++)
{
$(stepSelector).hide(stepSpeed).removeClass(stepClass).addClass(hiddenStepClass);
}
changeStep(currentStep,currentStep+1);
currentStep = currentStep+1;
checkForMore();
return false;
});
//bind prev step
$(prevButton).bind("click",function ()
{
for (var i=0;i<fieldMovementsPerStep;i++)
{
$(hiddenStepSelector).removeClass(hiddenStepClass).addClass(stepClass).show(stepSpeed);
}
changeStep(currentStep,currentStep-1);
currentStep = currentStep-1;
checkForMore();
return false;
});
//make all hidden
//$("div[id^=brief_]").hide();
//$("table[id^=brief_]").hide();
//$("div#brief_campaigne").show();
//$("div#brief_project_description").show();
//steps
checkForMore();
loading(false);

//handle tab
$("input[id$=rbOther]").keydown(function(event){
  if (event.keyCode == 9 && !$("input[id$=rbOther]").attr('checked')) {
        for (var i=0;i<fieldMovementsPerStep;i++)
        {
        $(stepSelector).hide(stepSpeed).removeClass(stepClass).addClass(hiddenStepClass);
        }
        changeStep(currentStep,currentStep+1);
        currentStep = currentStep+1;
        checkForMore();
         if ($.browser.firefox)
         {
            event.prevendDefault();
         }
         return false;
  }
});

$("input[id$=cblStyle_1],input[id$=txtLongevity],input[id$=txtImagery]").keydown(function(event){
  if (event.keyCode == 9) {
        for (var i=0;i<fieldMovementsPerStep;i++)
        {
        $(stepSelector).hide(stepSpeed).removeClass(stepClass).addClass(hiddenStepClass);
        }
        changeStep(currentStep,currentStep+1);
        currentStep = currentStep+1;
        checkForMore();
        if ($.browser.firefox)
         {
            event.prevendDefault();
         }
        return false;
  }
});
$("input[id$=rbOther],input[id$=cblStyle_1]").keyup(function (event) { if (event.keyCode == 9){return false;}});
$("input[id$=rbOther],input[id$=cblStyle_1]").keypress(function (event) { if (event.keyCode == 9){return false;}});


}

/* brief functions */
var hiddenStepSelector = "div[id^="+stepIdentifier+"]."+hiddenStepClass+":last";
var stepIdentifier = "brief_";
var fieldMovementsPerStep = 5;
var stepClass = "step";
var hiddenStepClass = "hiddenStep";
var nextButton = "div#nextStep";
var prevButton = "div#prevStep";
var currentStep = 1;
var stepSpeed = "fast";
var stepSelector = "div#[id^="+stepIdentifier+"]."+stepClass+":first";
var hiddenStepSelector = "div[id^="+stepIdentifier+"]."+hiddenStepClass+":last";
function changeStep(current,toChange)
{
    var findstr ;
    if (current == 0|| current == 1)
    {
    findstr= /step 1/;
    }
    else if (current == 2)
    {
    findstr= /step 2/;
    }
    else if (current == 3)
    {
    findstr= /step 3/;
    }
    else if (current == 4)
    {
    findstr = /step 4/;
    }
    else if (current == 5)
    {
    findstr = /step 5/;
    }
    var step = $("img[src*=step]").attr('src');
    step = step.toString().replace(findstr,"step "+toChange);
    $("img[src*=step]").attr('src',step);
}

function checkForMore()
{
    if ($(hiddenStepSelector).length == 0)
    {
    //hide previous
    $(prevButton).hide();
    }
    else
    {
    $(prevButton).show();
    }
    if ($(stepSelector).length == 0)
    {
        $(nextButton).hide();
    }
    else
    {
        $(nextButton).show();
    }
}

/* end brief functions */

function animateRequest()
{
    if ($.browser.msie)
    {
    $("input[id$=btnSend]").css('margin-right','10px');
    }
    //upload expansion
$("div#addUpload").bind("click",function ()
{
    if ($("tr.potentialFileUpload:first").length > 0)
    {
    $("tr.potentialFileUpload:first").removeClass("potentialFileUpload");
    var rowspan = $("div#addUpload").parent().parent().attr("rowspan");
    $("div#addUpload").parent().parent().attr("rowspan",rowspan+1).css("vertical-align","bottom");
    }
    else
    {
        $("div#addUpload").hide();
    }
});
    loading(false);
}

function animateContact()
{
    if ($.browser.msie)
    {
    $("input[id$=btnSend]").css('margin-right','21px');
    }
    loading(false);
}
var scrollHeight = 0;
function serviceScrollSpeed(dir,speed)
{
 if (scrollHeight == 0)
    {
        scrollHeight = calculateChildrensHeight($('div#innerPageContent'));
        $('div#innerPageContent').css('height',scrollHeight);
    }
    var bottom = $.browser.msie ? 590 : $.browser.safari ? 580 : 550;
    var ttop = $.browser.msie ? 270 : 270;
    var queue = $.browser.msie;
            if (($('div#innerPageContent').offset().top <= ttop || dir == '-') && (scrollHeight+ $('div#innerPageContent').offset().top >= bottom || dir == '+'))//if the height plus top > 522
        {
            var topRes = dir+"="+speed+"px";
            $('div#innerPageContent').animate({"top": topRes},{ queue:queue, duration:1 });
        }
}
function serviceScroll(dir)
{
   serviceScrollSpeed(dir,10);
}
function posMiddle()
{
var height = $(window).height();
var extraSpace = height - 600;
if (extraSpace > 0)
{
	$("div#container").css({'position':'relative','top':Math.round(extraSpace/2)});
}
}
function posContent()
{
var left = $("div#container").offset().left;
var top = $("div#container").offset().top;
$("div#mainContent").css({"left":Math.round(left+330)+"px","top":top+"px"});
}
function onResize()
{
posMiddle();
//posContent();
}
$(document).ready(function () {
if (currentSite == "counton")
{
    forceAjaxGoTo('/who-we-are.aspx');
}
else
{
    forceAjaxGoTo('/countonline-who-we-are.aspx');
}
});
