﻿// jQuery plugin: PutCursorAtEnd 1.0
// http://plugins.jquery.com/project/PutCursorAtEnd
// by teedyay
//
// Puts the cursor at the end of a textbox/ textarea
// codesnippet: 691e18b1-f4f9-41b4-8fe8-bc8ee51b48d4
(function($)
{
    jQuery.fn.putCursorAtEnd = function()
    {
        return this.each(function()
        {
            $(this).focus()
            // If this function exists...
            if (this.setSelectionRange)
            {
                // ... then use it
                // (Doesn't work in IE)
                // Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
                var len = $(this).val().length * 2;
                this.setSelectionRange(len, len);
            }
            else
            {
                // ... otherwise replace the contents with itself
                // (Doesn't work in Google Chrome)
                $(this).val($(this).val());
            }
            // Scroll to the bottom, in case we're in a tall textarea
            // (Necessary for Firefox and Google Chrome)
            this.scrollTop = 999999;
        });
    };
})(jQuery);


var varROI = new Array(
    0.5636,
    0.1345,
    0.0982,
    0.0400,
    0.0473,
    0.0327,
    0.0036,
    0.0291,
    0.0145,
    0.0255);

var ImgStep1Text = "/images/seo_calculator/scene1_text_off.png"
    , ImgStep1TextRed = "/images/seo_calculator/scene1textbox_red.png"
    , ImgStep2Text = "/images/seo_calculator/scene2textbox.png"
    , ImgStep2TextRed = "/images/seo_calculator/scene2textbox_red.png"
    , ImgStep3Text = "/images/seo_calculator/scene3textbox.png"
    , ImgStep3TextRed = "/images/seo_calculator/scene3textbox_red.png"
    , ImgShowMeOn = "/images/seo_calculator/updated_showme_on.png"
    , ImgShowMeOff = "/images/seo_calculator/updated_showme.png";

$(document).ready(function() {
    /* Preload images */
    MM_preloadImages(ImgStep1Text, ImgStep1TextRed, ImgStep2Text, ImgStep2TextRed, ImgStep3Text, ImgStep3TextRed, ImgShowMeOn, ImgShowMeOff, "/images/ajaxloader.gif");

    /* Hide validation */
    $(".validation").hide();

    /* Configure scrollable areas */
    var scrollableroot = $("#wizard").scrollable({ size: 1, easing: "swing", clickable: false });

    /* Configure validation */
    var api = scrollableroot.scrollable();

    //    /* validation logic is done inside the onBeforeSeek callback */
    api.onBeforeSeek(function(event, i) {
        /* we are going 1 step backwards so no need for validation */
        if (api.getIndex() < i) {
            var isValid = false;
            if (api.getIndex() == 0)
                isValid = validateStep1();
            else if (api.getIndex() == 1)
                isValid = validateStep2();
            else if (api.getIndex() == 2)
                isValid = validateStep3();

            /* if there are empty fields, then  */
            if (!isValid) {

                /* cancel seeking of the scrollable by returning false */
                return false;

                /* everything is good  */
            } else {
                return true;
            }

        }

    });

    /* validation logic is done inside the onBeforeSeek callback */
    api.onSeek(function(event, i) {
        // focus on first textbox and put cursor at the end
        var page = scrollableroot.find(".page").eq(i);
        page.find(":input").first().putCursorAtEnd()        
    });

    /* Configure result overlay */
    var triggers = $("#showResult").overlay({

        absolute: false,

        /* some expose tweaks suitable for modal dialogs */
        expose: {
            color: '#333',
            loadSpeed: 200,
            opacity: 0.9
        },

        /* another property */
        top: 0,

        closeOnClick: true,

        /* hide trigger when the overlay is opened  */
        onBeforeLoad: function(event) {
            if (validateStep3()) {
                return true;
            }
            else
                return false;
        },

        onLoad: function(event) {
            setupCalculatorResults();
        }

    });

    /* if tab is pressed seek to next page */
    scrollableroot.find(":input").keydown(function(e) {
        if (e.keyCode == 9 || e.keyCode == 13) {
            /* seeks to next tab by executing our validation routine */
            api.next();
            e.preventDefault();
        }
    });

    scrollableroot.find(".page").find(".scene1text").focus();


    // When user types in value, prepend with pound symbol
//    $(".scene3text").bind("keydown", function() {
//        var value = $(".scene3text").val();
//        if (!value.startsWith("£")) {
//            $(".scene3text").val("£" + value);
//        }
//    });

});

String.prototype.startsWith = function(s) { return (this.match("^" + s) == s) }

function setupCalculatorResults() {
    var keyword = $(".scene1text").val();
    var ratio = $(".scene2text").val();
    var conversion = $(".scene3text").val();

    $("#seoCalculatorKeyword").text(keyword);
    AdwordsService.GetGlobalKeywordSearchVolume(keyword, onCompleteGetGlobalKeywordSearchVolume, onCompleteGetGlobalKeywordSearchVolumeFailure);

    $("#flashcontent").html(generateLoadingHTML());
    $("#resultsTable").html(generateLoadingHTML());
}

function onCompleteGetGlobalKeywordSearchVolumeFailure(ex) 
{
    $("#flashcontent").html("<div style='text-align:center; padding-top:50px;'>There was a problem during the calculation. Please try again or contact support.</div>");
    $("#resultsTable").html("");    
}


function onCompleteGetGlobalKeywordSearchVolume(returnValue) {
    if (returnValue != 0) {
        var keyword = $(".scene1text").val();
        var ratio = $(".scene2text").val();
        var conversion = $(".scene3text").val();

        var arrRankingRevenues = calculateROI(returnValue, ratio, conversion);

        generateBarChart(arrRankingRevenues);
        $("#resultsTable").html(generateResultsTable(arrRankingRevenues));
    }
    else {
        $("#flashcontent").html("<div style='text-align:center; padding-top:50px;'>There are not enough searches for the keyword you entered. Please try a different one.</div>");
        $("#resultsTable").html("<div style='text-align:center; padding-top:50px;'>There are not enough searches for the keyword you entered. Please try a different one.</div>");
    }
}

function calculateROI(monthlyTraffic, ratio, value) {
    var ar = new Array();
    for (i = 0; i < 10; i++) {
        ar.push((monthlyTraffic) * (ratio / 100) * value * varROI[i]);
    }

    return ar.join(",");
}

/* Generate graph xml */
function generateBarChart(x) {
    var requiredMajorVersion = 9;
    var requiredMinorVersion = 0;
    var requiredRevision = 0;

    var hasRightVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
    if (!hasRightVersion) {
        $("#flashcontent").html(
            "<div style='width:100%; text-align:center; padding-top:40px;'>"        
        + "<br />This content requires the Adobe Flash Player. <a href='http://www.adobe.com/go/getflash/' target='_blank'>Get Flash</a>" 
        + "</div>");

        return;
    }

    var arr = x.split(",");
    if (arr.length == 10) {
        var so = new SWFObject("/includes/calculator/amcolumn/amcolumn.swf", "amcolumn", "770px", "250px", "8");
        so.addVariable("path", "/includes/calculator/amcolumn/");
        so.addVariable("settings_file", encodeURIComponent("amcolumn_settings.xml"));
        so.addVariable("data_file", encodeURIComponent("amcolumn_data.xml"));
        so.addVariable("preloader_color", "#ffffff");
        so.addParam("wmode", "transparent");


        so.addVariable("chart_settings", encodeURIComponent("<settings><font>calibri</font><text_size>13</text_size><redraw>1</redraw><colors>FCD202,B0DE09,0D8ECF,2A0CD0,CD0D74,CC0000,00CC00,0000CC,DDDDDD,999999,333333,990000</colors><preloader_on_reload>1</preloader_on_reload><add_time_stamp>1</add_time_stamp><thousands_separator>,</thousands_separator><decimals_separator>.</decimals_separator><digits_after_decimal>0</digits_after_decimal><precision>2</precision><background><alpha>100</alpha><file>http://dev.dotseo.co.uk/images/chart_background.jpg</file></background><plot_area><margins><left>80</left><right>40</right><top>20</top><bottom>60</bottom></margins></plot_area><grid><category><color>FFFFFF</color><alpha>10</alpha><dashed>1</dashed></category><value><color>CCCCCC</color><alpha>10</alpha><dashed>1</dashed></value></grid><axes><category><tick_length>6</tick_length><width>1</width><color>CCCCCC</color><alpha>98</alpha></category><value><tick_length>6</tick_length><width>1</width><color>E7E7E7</color></value></axes><values><category><color>666666</color><text_size>13</text_size></category><value><color>666666</color><text_size>10</text_size><min>0</min><skip_first>0</skip_first><unit>£</unit><unit_position>left</unit_position></value></values><balloon><color>FFFFFF</color><text_color>4490A5</text_color><max_width>167</max_width><corner_radius>7</corner_radius><border_width>4</border_width><border_color>4490A5</border_color><border_alpha>45</border_alpha></balloon><legend><enabled>0</enabled><margins>4</margins><reverse_order>1</reverse_order><key><size>19</size></key></legend><column><type>3d column</type><width>85</width><spacing>10</spacing><border_color>666666</border_color><border_alpha>17</border_alpha><hover_brightness>60</hover_brightness><hover_color>4490A5</hover_color><corner_radius_top>10</corner_radius_top><balloon_text>Estimated revenue: £{value}</balloon_text><data_labels_text_size>15</data_labels_text_size><data_labels_always_on>1</data_labels_always_on><grow_time>1.5</grow_time><grow_effect>strong</grow_effect><sequenced_grow>1</sequenced_grow></column><angle>0</angle><line><width>3</width><fill_alpha>61</fill_alpha><bullet>round</bullet><bullet_size>3</bullet_size></line><export_as_image><file>seo_graph</file></export_as_image><graphs><graph gid='0'><title>Google Page Ranking</title><color>000000</color><gradient_fill_colors>eb4a5a, d8979d, ffffff</gradient_fill_colors><visible_in_legend>0</visible_in_legend></graph><graph gid='1'><title>Column</title><color>7F8DA9</color></graph><graph gid='2'><title>Line</title></graph></graphs><labels><label lid='0'><text>Google Page Ranking</text><y>220</y><text_color>000000</text_color><text_size>12</text_size><align>center</align></label></labels></settings>"));
		
		
		
        so.addVariable("chart_data", encodeURIComponent("<chart><series><value xid='0'>#10</value><value xid='1'>#9</value><value xid='2'>#8</value><value xid='3'>#7</value><value xid='4'>#6</value><value xid='5'>#5</value>													<value xid='6'>#4</value><value xid='7'>#3</value><value xid='8'>#2</value><value xid='9'>#1</value></series><graphs><graph gid='0'>"
         + "<value xid='0'>" + Math.round(parseFloat(arr[9])) + "</value>"
         + "<value xid='1'>" + Math.round(parseFloat(arr[8])) + "</value>"
         + "<value xid='2'>" + Math.round(parseFloat(arr[7])) + "</value>"
         + "<value xid='3'>" + Math.round(parseFloat(arr[6])) + "</value>"
         + "<value xid='4'>" + Math.round(parseFloat(arr[5])) + "</value>"
         + "<value xid='5'>" + Math.round(parseFloat(arr[4])) + "</value>"
         + "<value xid='6'>" + Math.round(parseFloat(arr[3])) + "</value>"
         + "<value xid='7'>" + Math.round(parseFloat(arr[2])) + "</value>"
         + "<value xid='8'>" + Math.round(parseFloat(arr[1])) + "</value>"
         + "<value xid='9'>" + Math.round(parseFloat(arr[0])) + "</value>"
         + "</graph><graph gid='1'><value xid='0'/><value xid='1'/><value xid='2'/><value xid='3'/><value xid='4'/><value xid='5'/><value xid='6'/><value xid='7'/><value xid='8'/><value xid='9'/></graph><graph gid='2'><value xid='0'/><value xid='1'/><value xid='2'/><value xid='3'/><value xid='4'/><value xid='5'/><value xid='6'/><value xid='7'/><value xid='8'/><value xid='9'/></graph></graphs></chart>"));

        so.write("flashcontent");
    }
}

function generateResultsTable(x) {
    var arr = x.split(",");
    if (arr.length == 10) {
        var html = "<table style='width:100%;'>";
        html += "<thead><td align='center'>Google ranking</td ><td align='right'>Revenue*</td><td width='40px'></td></thead>";
        for (i = 10; i > 0; i--)
        {
            html += "<tr" + (i%2 == 0 ? " class='tr_alt' " : "") + "><td align='center'>" + i + "</td><td align='right'>£" + addCommas(Math.round(parseFloat(arr[i-1]))) + "</td><td></td></tr>";
        }
        html += "</table>";
        return html;
    }

    return "";
}

function addCommas(value ) {
    var sValue = value + "";
    var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})');

    while(sRegExp.test(sValue)) {
        sValue = sValue.replace(sRegExp, '$1,$2');
    }
    return sValue;
} 

function generateLoadingHTML(x) {
    return "<div style='width:100%; text-align:center; padding-top:40px;'><img src='/images/ajaxloader.gif' title='Loading' style='vertical-align:middle;' alt='loading' /><div class='loadingText' style='width:100%'>Please wait while we are loading your data ...</div></div>";
}


function validateStep1() {
    var page = $(".page").eq(0);
    inputs = page.find(".scene1text");

    var isValid = false;

    inputs.filter(function () {
        if ($(this).val().length > 0 && $(this).val() != "e.g. 'email marketing in london'")
            isValid = true;
    });

    if (!isValid) {
        $(".textarea1").css('backgroundImage', 'url("' + ImgStep1TextRed + '")');
        page.find(".validation").slideDown();
    }
    else {
        $(".textarea1").css('backgroundImage', 'url("' + ImgStep1Text + '")');
        page.find(".validation").hide();
    }

    // if valid focus cursor on next textbox
    if (isValid)
        page.find(".scene2text").focus();
        
    return isValid;
}

function validateStep2() {
    var page = $(".page").eq(1);
    inputs = page.find(".scene2text");

    var isValid = false;

    inputs.filter(function () {
        if ($(this).val().length > 0 && $(this).val() != "e.g. 2" && $(this).val() > 0 && $(this).val() <= 100)
            isValid = true;
    });

    if (!isValid) {
        $(".textarea2").css('backgroundImage', 'url("' + ImgStep2TextRed + '")');
        page.find(".validation").slideDown();

        /* enabled next button rollover */
        page.find(".button_next").attr("rolloverenabled", "true");
        page.find(".button_next").attr({ src: '/images/seo_calculator/next_no.png' });
    }
    else {
        $(".textarea2").css('backgroundImage', 'url("' + ImgStep2Text + '")');
        page.find(".validation").hide();

        /* disable next button rollover */
        page.find(".button_next").attr("rolloverenabled", "false");
        page.find(".button_next").attr({ src: '/images/seo_calculator/next_on.png' });
    }

    return isValid;
}

function validateStep3() {
    var page = $(".page").eq(2);

    inputs = page.find(".scene3text");
    var isValid = false;

    inputs.filter(function() {
        if ($(this).val().length > 0 && $(this).val() != "e.g. £36" && $(this).val() > 0)
            isValid = true;
    });

    if (!isValid) {
        $(".textarea3").css('backgroundImage', 'url("' + ImgStep3TextRed + '")');
        page.find(".validation").slideDown();
    }
    else {
        $(".textarea3").css('backgroundImage', 'url("' + ImgStep3Text + '")');
        page.find(".validation").hide();
    }

    return isValid;
}



