$(function() {

    $(document).ready(function() {
        $('#mainNav, .login_box').show();
    });

    getVars();

    $('a.tblank').attr('target','_blank');

    if ($.browser.msie && $.browser.version.substr(0,1)<7) {
        $('.btn_signup span,.btn_login_toggle, h1 a img, .txt_jointhenum1affiliatenetwork, .pub_adv_box, .logos, .clickbooth span, .integraclick span, .seal1, .follow_us_bg, .login_box .login_edge.left_edge').supersleight();

        if ($('body').is ('.home')) {
            var zIndexNumber = 1000;
            $('div').each(function() {
                $(this).css('zIndex', zIndexNumber);
                zIndexNumber -= 10;
            });
        }

    }

    $("#login-tabs").tabs().ready(function() {
        $('#login-tabs .ui-tabs-nav li div.select').each(function() {
            $(this).append('<a title="CPA" class="select" href="#select">CPA</a><ul><li><a title="CPA" href="#">CPA</a></li><li><a title="CPC" href="#">CPC</a></li></ul>');
        }).ready(function() {
            bindLogin();
        });
    });

    $('#login-tabs .ui-tabs-nav .ui-state-default, #login-tabs .ui-tabs-nav .ui-state-default *').live('click', function() {

        if($(this).is('.ui-state-default')){
            $(this).find('a.tab-trigger').trigger('click');
        } else {
            turnOnTab($(this))
        }

    });

    $("a[href=#forgotpass]").click(function() {
        openWin("https://publishers.clickbooth.com/forgot_password.html");
    });

    $(document).click(function(event) {
        var target = $(event.target);

        if (!target.attr('id').match(/^sp/) && target.parents('#sp').length == 0 && !target.attr('class').match(/^cpa no-type/)) {
            closePopup();
        }
    });

    $('.btn_signup, .btn_startnow, .btn_learnmore').not('.default-btn').click(function(event) {
        event.stopPropagation();
        chooseNetworkType(this, $(this).attr('href'), event);
    });

    /*Login Functionality*/
    bindToggleLogin();
    mainNav();

    if (typeof(initial_number) !== 'undefined'  && typeof(increment_number) !== 'undefined' && $('#eCounter').length != 0) {
        eCounter('#eCounter', initial_number, increment_number);
    }

    $('.abtn1').click(function(e) {
        e.preventDefault();
        var advpub = $(this).parent().parent().parent().attr('id');
        if(advpub == 'login_advertisers') {
            switch ($(this).children().text()) {
                case 'CPA Sign Up':
                    window.location ='/advertiser/signup';
                    break;
                case 'CPC Sign Up':
                    window.location = 'http://cpc.clickbooth.com/signup/advertiser/index/step/1';
                    break;
            }
        } else if (advpub == 'login_publishers') {
            switch ($(this).children().text()) {
                case 'CPA Sign Up':
                    window.location = 'https://my.clickbooth.com/signup/';
                    break;
                case 'CPC Sign Up':
                    window.location = 'http://clickbooth.com/cbcpcsignup.php';
                    break;
            }
        }
    })
});

var loginBoxDefaultZ;

function getVars() {
    loginBoxDefaultZ = parseInt($('.login_box').css('z-index'));
}

function closePopup() {
    $('#sp').fadeOut(300, function() { $(this).remove(); });
}

function chooseNetworkType(btn, tag, e) {
    var pop, type = tag.split('#'), btn_pos = $(btn).offset(),
    hasType, left_pos, top_pos, wrap,
    cpaPub   = "https://my.clickbooth.com/signup/",
    cpcPub   = "http://clickbooth.com/cbcpcsignup.php",
    cpaAdv   = "/advertiser/signup",
    cpcAdv   = "http://cpc.clickbooth.com/signup/advertiser/index/step/1",
    lmCpaAdv = "/advertiser/cpa",
    lmCpaPub = "/publisher/cpa",
    lmCpcAdv = "/advertiser/cpc",
    lmCpcPub = "/publisher/cpc",
    link_1, link_2;

    switch (type[1]) {
        case 'pub':
            link_1   = cpaPub;
            link_2   = cpcPub;
            left_pos = btn_pos.left - 111;
            top_pos  = btn_pos.top + 25;
            hasType  = "";
            wrap     = "";

            break;

        case 'adv':
            link_1   = cpaAdv;
            link_2   = cpcAdv;
            left_pos = btn_pos.left - 111;
            top_pos  = btn_pos.top + 25;
            hasType  = "";
            wrap     = "";

            break;

        case 'startnow_cbcpc':
            link_1   = cpcPub;
            link_2   = cpcAdv;
            left_pos = btn_pos.left - 8;
            top_pos  = btn_pos.top + 25;
            hasType  = "pre-type-cpc";
            wrap     = "type-found";

            break;

        case 'startnow_cbcpa':
            link_1   = cpaPub;
            link_2   = cpaAdv;
            left_pos = btn_pos.left - 8;
            top_pos  = btn_pos.top + 25;
            hasType  = "pre-type-cpa";
            wrap     = "type-found";

            break;

        case 'learnmore_cpc':
            link_1   = lmCpcPub;
            link_2   = lmCpcAdv;
            left_pos = btn_pos.left - 8;
            top_pos  = btn_pos.top + 25;
            hasType  = "pre-type-cpa";
            wrap     = "type-found-learn-cpc";

            break;

        case 'learnmore_cpa':
            link_1   = lmCpaPub;
            link_2   = lmCpaAdv;
            left_pos = btn_pos.left - 8;
            top_pos  = btn_pos.top + 25;
            hasType  = "pre-type-cpa";
            wrap     = "type-found-learn-cpa";

            break;

        case 'signup':
        default :
            link_1   = "#cpa";
            link_2   = "#cpc";
            left_pos = btn_pos.left - 200;
            top_pos  = btn_pos.top + 18;
            hasType  = "no-type";
            wrap     = "type-not-found";

            break;
    }

    pop = '<div id="sp" class="signup-popup ' + wrap + '"><a class="close" title="close" href="#"></a>' +
            '<a class="cpa ' + hasType + '" title="CPA Network" href="' + link_1 + '"></a>' +
            '<a class="cpc ' + hasType + '" title="CPC Network" href="' + link_2 + '"></a></div>';

    $('#sp').remove();
    $('body').append(pop);
    $('#sp').css({ left: left_pos, top: top_pos });

    $('.no-type, .pre-type-cpa, .pre-type-cpc').click(function(event) {
        var url = $(this).attr('href'), cType = url.split('#'),
            pub = "class='pub' title='Publisher'",
            adv = "class='adv' title='Advertiser'",
            pubCPA = '<a ' + pub + ' href="' + cpaPub + '"></a>',
            pubCPC = '<a ' + pub + ' href="' + cpcPub + '"></a>',
            advCPA = '<a ' + adv + ' href="' + cpaAdv + '"></a>',
            advCPC = '<a ' + adv + ' href="' + cpcAdv + '"></a>';

        $('#sp.type-not-found').css('background-position','0 -91px');
        $('#sp a').eq(1).remove();
        $('#sp a').eq(2).remove();

        if (cType[1] == "cpa") {
            $(pubCPA).insertAfter('#sp .close');
            $(advCPA).insertAfter('#sp .pub');
        } else {
            $(pubCPC).insertAfter('#sp .close');
            $(advCPC).insertAfter('#sp .pub');
        }
    });

    $('#sp .close, .btn_login_toggle .btn').click(function(event) {
        event.preventDefault();
        closePopup();
    });

}

function turnOnTab(element) {
    $(element).parents('.ui-state-default').find('a.tab-trigger').trigger('click');
}

function bindLogin() {
    //select-login-type
    $('#login-tabs .select a').bind('click',function() {
        turnOnTab($(this));
        $(this).next().toggleClass('on');
        if ($(this)[0].innerHTML == 'CPC') {
            $("a[href=#forgotpass]").unbind('click', false).click(function() {
                window.location = "http://cpc.clickbooth.com/?pageid=account&subpid=forgot_password";
            });
        } else {
            $("a[href=#forgotpass]").unbind('click', false).click(function() {
                openWin("https://publishers.clickbooth.com/forgot_password.html");
            });
        }
        return false;
    }).next().find('a').bind('click',function() {
        var container = $(this).parents('div.select:first').next('a').attr('href');

        $(this).parent().parent().toggleClass('on');
        $(this).parent().parent().prev().text($(this).text());

        $('.login-signup > a > span', $(container)).text($(this).text() + ' Sign Up');

        return false;
    });
}

var loginCalled = false;
function submitLogin(rel) {
    if (!rel) {
        return false;
    }
    if (loginCalled) {
        return true;
    }
    loginCalled = true;
    var f = $(rel).is("form") ? $(rel) : $(rel).parents('form:last'),
        type = f.attr('id').substr(6),
        netw = $("a[href$=" + type + "]").prev().find('a[href=#select]:first').text().toLowerCase();

    if (netw == 'cpc') {
        f.attr('action','http://cpc.clickbooth.com/')
            .append($('<input type="hidden" name="action" value="login"/>'))
            .find('input[type=text]')
                .attr('name','username')
                .end()
            .find('input[type=password]')
                .attr('name','password')
        ;
    }
    else {
        f.attr('action','https://publishers.clickbooth.com/')
            .append($('<input type="hidden" name="next" value="/"/>'))
        ;
    }
    f[0].submit();
    return true;
}

//Login Box Toggle
function bindToggleLogin() {
    $('a[href=#t_login]').bind('click.toggleLoginBox',function() {
        $('a[href=#t_login]').unbind('click.toggleLoginBox');
        if (!$(this).find('.switch').hasClass('on')) {
            $('.login_box').css('z-index',6);
            $('.login_box').animate({
                top: '+='+$('.login_form').height()
            }, 500, function() {
                $(this).find('.switch').addClass('on');
                bindToggleLogin();
            });
        } else {
            $('.login_box').animate({
                top: '-='+$('.login_form').height()
            }, 500, function() {
                $(this).find('.switch').removeClass('on');
                bindToggleLogin();
                $('.login_box').css('z-index',loginBoxDefaultZ);
            });
        }
        return false;
    });
};

function mainNav() {
  var largestWidth = 0;
  var setWidths = ['Publisher Solutions','Advertiser Solutions','My Clickbooth'];
  setWidths['Advertiser Solutions'] = {'width': 156};
  setWidths['Publisher Solutions'] = {'width': 148};
  setWidths['My Clickbooth'] = {'width': 160};

  //set widths of all anchors
  $('#mainNav li.level0').each(function(i) {
    $('#mainNav li.level0:eq('+i+') > *:first').each(function(j) {
      //check for predefined widths
      if($.inArray($(this).text(),setWidths) != -1) {
        largestWidth = setWidths[$(this).text()].width;
      } else if ($(this).width() > largestWidth) {
        largestWidth = $(this).width();
      }
    }).ready(function(elm) {
      $('#mainNav li.level0:eq('+i+') a, #mainNav li.level0:eq('+i+') span').width(largestWidth);
      largestWidth = 0;
    });
  }).ready(function() {
    $('#mainNav li.level0').css('position','relative');
  });

  var liHeights = [];
  var shadowLeft = [];

  //bind all anchors
  $('#mainNav li.level0').each(function(i) {
    $(this).find('ul li:eq('+(parseInt($(this).find('ul li').length-1))+')').addClass('last');

    if ($(this).find('ul').length) {

      var defaultAHeight = $(this).find('span:eq(0),a.multi:eq(0)').height() +
        parseInt($(this).find('span:eq(0),a.multi:eq(0)').css('padding-top'))+
        parseInt($(this).find('span:eq(0),a.multi:eq(0)').css('padding-top'));

      liHeights.push($(this).find('ul').height()+(defaultAHeight));

      //mouseevents : over
      $(this).mouseenter(function(e) {
        $(this).prev().find('span:eq(0),a.multi:eq(0)').css('border-right','0');
        $(this).find('span[rel=level0],a[rel=level0]').addClass('multi_active').removeClass('multi');
        if(!$(this).is(':animated')) {
          $(this).stop().animate({
            height: liHeights[i]
          },'fast');
        }

        $(this).addClass('shadow');
      });

      //and : out
      $(this).bind('mouseleave',function() {
        $(this).removeClass('shadow');

        $(this).prev().find('span:eq(0),a.multi:eq(0)').css('border-right','1px solid #CCCCCC');
        $(this).find('span[rel=level0],a[rel=level0]').addClass('multi').removeClass('multi_active');
        $(this).stop().height(defaultAHeight);
      });

    }
  });
}

function eCounter(counterID, startingNumber, incrementNumber) {
    if (typeof(startingNumber) === 'undefined') {
        $(counterID).parent().remove();

        return;
    }

    $(counterID).empty().prepend('<li id="dollarsign">&nbsp;</li>')
    // Array to hold each digit's starting background-position Y value
    var initialPos = [0, -126, -252, -378, -504, -630, -756, -882, -1008, -1134];
    // Amination frames
    var animationFrames = 5;
    // Frame shift
    var frameShift = 27;

    // Starting number
    // If no number in URL (?n=number), then get a random one
    var theNumber = startingNumber;
    // Or you could get it via AJAX:
    // var theNumber = Number($.ajax({ type: "GET", url: "number.php", async: false }).responseText);
    // Where number.php can be a DB query, or any kind of script that outputs a number to use

    // Increment
    var increment = (typeof(incrementNumber) !== 'undefined') ? incrementNumber : 1;
    // Pace of counting in milliseconds
    var pace = 1000;

    // Initializing variables
    var digitsOld = [], digitsNew = [], subStart, subEnd, x, y;

    // Function that controls counting
    function doCount(){
        // In this example, we're padding the numbers
        var x = pad(theNumber.toString());
        theNumber += increment;

        var y = pad(theNumber.toString());
        digitCheck(x,y);
    }

    // This checks the old count value vs. new value, to determine how many digits
    // have changed and need to be animated.
    function digitCheck(x,y){
        if (y.length > x.length) addDigit(y.length);
        var digitsOld = splitToArray(x),
        digitsNew = splitToArray(y);
        for (var i = 0, c = digitsNew.length; i < c; i++){
            if (digitsNew[i] != digitsOld[i]){
                animateDigit(i, digitsOld[i], digitsNew[i]);
            }
        }
    }

    // Animation function
    function animateDigit(n, oldDigit, newDigit){
        // I want three different animations speeds based on the digit,
        // because the pace and increment is so high. If it was counting
        // slower, just one speed would do.
        // 1: Changes so fast is just like a blur
        // 2: You can see complete animation, barely
        // 3: Nice and slow
        var speed;
        switch (n){
            case 0:
                speed = pace/8;
                break;
            case 1:
                speed = pace/4;
                break;
            default:
                speed = pace/2;
                break;
        }
        // Cap on slowest animation can go
        speed = (speed > 100) ? 100 : speed;
        // Get the initial Y value of background position to begin animation
        var pos = initialPos[oldDigit];
        // Each animation is 5 frames long, and 103px down the background image.
        // We delay each frame according to the speed we determined above.
        for (var k = 0; k < animationFrames; k++){
            pos = pos - frameShift;
            if (k == (animationFrames - 1)){
                $("#d" + n).delay(speed).animate({
                    'background-position': '0 ' + pos + 'px'
                }, 0, function(){
                    // At end of animation, shift position to new digit.
                    $("#d" + n).css({
                        'background-position': '0 ' + initialPos[newDigit] + 'px'
                    }, 0);
                });
            }
            else{
                $("#d" + n).delay(speed).animate({
                    'background-position': '0 ' + pos + 'px'
                }, 0);
            }
        }
    }

    // Splits each value into an array of digits
    function splitToArray(input){
        var digits = new Array();
        for (var i = 0, c = input.length; i < c; i++){
            var subStart = input.length - (i + 1),
            subEnd = input.length - i;
            digits[i] = input.substring(subStart, subEnd);
        }
        return digits;
    }

    // Adds new digit
    function addDigit(len){
        var li = Number(len) - 1;
        if (li % 3 == 0) {
            $('<li class="seperator"></li>').insertAfter(counterID+' li#dollarsign');
        }

        $('<li id="d' + li + '"></li>');
        $("#d" + li).css({
            'background-position': '0 ' + initialPos[1] + 'px'
        });
    }

    // Sets the correct digits on load
    function initialDigitCheck(initial){
        // Creates the right number of digits
        // In this example, we're padding the numbers
        var padded = pad(initial.toString());
        var count = padded.length;
        var bit = 1;
        for (var i = 0; i < count; i++){
            $('<li id="d' + i + '"></li>').insertAfter(counterID+' li#dollarsign');
            if (bit != (count) && bit % 3 == 0) $('<li class="seperator"></li>').insertAfter(counterID+' li#dollarsign');
            bit++;
        }

        // Sets them to the right number
        var digits = splitToArray(initial.toString());

        for (var i = 0, c = digits.length; i < c; i++) {
            $("#d" + i).css({
                'background-position': '0 ' + initialPos[digits[i]] + 'px'
            });
        }
    }

    // Generates a good random number
    function getRandom(){
        var numD = Math.floor(Math.random()*9) + 3;
        var num = '';
        for (var i = 0; i < numD; i++){
            num += Math.floor(Math.random()*9).toString();
        }
        return num
    }

    // http://www.electrictoolbox.com/pad-number-zeroes-javascript/
    function pad(str, length) {
        var size = 11; // For 72 billion

        while (str.length < size) {
            str = '0' + str;
        }

        return str;
    }

    // Start it up
    initialDigitCheck(theNumber);
    setInterval(doCount, pace);

}

function openWin(url) {
	aWindow = window.open(url,"thewindow",'toolbar=0,location=0,directories=0,status=0,menubar=0, width=400, height=400, scrollbars, resizable');
	aWindow.focus();
}


