﻿var toggleKL = false;
var notificationTimer1;
var notificationTimer2;
var notificationTimer3;

function showProcessingText(processingText, showProcessingTextAsModal) {
    setTimeout("showMaskMessage('" + processingText + "','" + showProcessingTextAsModal + "');", 100);
}

function showMaskMessage(processingText, showProcessingTextAsModal) {
    var maskHeight = $(window).height() + $(document).scrollTop();
    var maskWidth = $(window).width() + $(document).scrollLeft();

    if (showProcessingTextAsModal) {
        $('#Mask').css({ 'width': maskWidth, 'height': maskHeight });
        $('#Mask').fadeIn(100);
        $('#Mask').fadeTo('fast', 0.4);
    }

    var toLeft = (processingText.length * 8) / 2;

    $('#ProcessingText').css({
        'left': ($(window).width() / 2) - toLeft + 'px',
        'display': 'block',
        'top': $(window).height() / 2 + 'px',
        'zIndex': 90001
    });

    $('#ProcessingText').html(processingText);
}

function hideMask() {
    setTimeout(function () {
        $('#Mask').hide();
        $('#ProcessingText').hide();
    }, 200);
}

function showNotification(text, position) {

    $('#NotificationText').html(text);

    var toLeft = (text.length * 8) / 2;

    if(position == 'top')
    {
        $('#NotificationText').css({
            'left': ($(window).width() / 2) - toLeft + 'px',
            'display': 'block',
            'zIndex': 90002
        });
    }
    else if(position == 'middle')
    {
             $('#NotificationText').css({
            'left': ($(window).width() / 2) - toLeft + 'px',
            'top': $(window).height() / 2 + 'px',
            'display': 'block',
            'zIndex': 90002
        });
    }

    clearTimeout(notificationTimer1);
    clearTimeout(notificationTimer2);
    clearTimeout(notificationTimer3);

    notificationTimer1 = setTimeout(function () {       
        $('#NotificationText').fadeIn(500);       
    }, 200);


   notificationTimer2 = setTimeout(function () {        
        $('#NotificationText').fadeOut(500);
    }, 4000);

    notificationTimer3 = setTimeout(function () {
        $('#NotificationText').html('');
    }, 4500);

}

var totalRecords = 0;
var pageSize = 0;

function initDataTable(selectorName, processingScript) {

    var iCurrentPage = 0;
    var aoColumns = [];

    $(selectorName + ' thead th').each(function () {
        if ($(this).hasClass('no-sort')) {
            aoColumns.push({ "bSortable": false, "sWidth": $(this).width(), "sClass": $(this).attr('class') });
        } else {
            var sortType = "string";

            if ($(this).hasClass('numeric')) {
                sortType = "numeric"
            }

            aoColumns.push({ "sType": sortType, "sWidth": $(this).width(), "sClass": $(this).attr('class') });
        }
    });

    var minHeight = 320;

    if ($.browser.webkit) 
    {
        minHeight = $(document).height() - 320;
        
        if(minHeight < 320)
        {
		    minHeight = 320;	
        }
    }
    else if($.browser.msie)
    {
        minHeight = $(document).height() - 320;
        
        if(minHeight < 320)
        {
            minHeight = 320;	
        }
                
    }
    else if($.browser.mozilla)
    {
        minHeight = $(document).height() - 310;

        if(minHeight < 310)
        {
	        minHeight = 310;	
        }
    }

    //set height if showing filters
    if(IsShowingFilters == true && IsFilterHeightSet == false)
    {
        IsFilterHeightSet = true;

        var newHeight = 0;

        if ($.browser.webkit) {
            minHeight = minHeight - 260;

            if(minHeight < 320)
            {
		        minHeight = 320;	
            }

            toggleKL = true;   
        }
        else if($.browser.msie)
        {
            minHeight = minHeight - 235;
            toggleKL = true;

            if(minHeight < 320)
            {
                minHeight = 320;	
            }
        }
        else if($.browser.mozilla)
        {
            minHeight = minHeight - 240;

            toggleKL = true;

            if(minHeight < 310)
            {
	            minHeight = 310;	
            }
        }
    }

   var oTable = $(selectorName).dataTable({
        "aoColumns": aoColumns,
        "bPaginate": true,
        "bJQueryUI": true,
        "sScrollY": minHeight,
        "iDisplayStart": 0,
        "iDisplayLength": 50,
        //"sScrollY": 600,
        "sPaginationType": "full_numbers",
        "bProcessing": true,
        "bFilter": false, // this is the search
        "bServerSide": true,
        "bStateSave": true,
        "bAutoWidth": false,
        "bScrollInfinite": false,
        "sAjaxSource": processingScript,
        "oLanguage": {
            "sLengthMenu": "Show&nbsp;<select><option value='25'>25</option><option value='50'>50</option><option value='100'>100</option><option value='500'>500</option></select>&nbsp;Keywords",
            "sInfo": "Showing _START_ to _END_ of _TOTAL_ Keywords",
            "sInfoEmpty": "Showing 0 to 0 of 0 Keywords",
            "sZeroRecords": "No Keywords",
            "sProcessing": "processing...",

        },
        "fnCookieCallback": function (sName, oData, sExpires, sPath) {                

                //page always on first load
                oData.iStart = 0;
                return sName + "="+JSON.stringify(oData)+"; expires=" + sExpires +"; path=" + sPath;
        },
        "fnInitComplete": function () {
            // Toggle visibility on any heavyweight items to prevent the flash of unstyled content
            
                               
        },
        "fnFooterCallback": function () {
            // Toggle visibility on any heavyweight items to prevent the flash of unstyled content   
        },
        "fnDrawCallback": function () {
            $('#KeywordCount').html("Keywords: (" + $('#keyword-phrase-table_info').text() + ")");
         
                              
            //shift click checkbox
            $('.shiftCheckBox').shiftcheckbox();
                    

            //show row style
            $('.chkKeyword').bind("click", function () {
                    
                if($(this).is(':checked'))
                {
                    //alert('checked');
                    $(this).parent().parent().addClass('rSelected');
                }
                else {
                    if($(this).parent().parent().hasClass('rSelected'))
                    {
                        $(this).parent().parent().removeClass('rSelected');
                    }
                }

                ShowSelectedKeywords();
            });

            //Copy to clipboard
//            $('img.lnkCopy').each(function (){

//                //Create a new clipboard client
//                var clip = new ZeroClipboard.Client();
//                //clip.setHandCursor(true);

//                clip.glue(this, $(this).parent().attr('id'));
//                clip.setText($(this).attr('keyword'));

//                //Add a complete event to let the user know the text was copied
//                clip.addEventListener('complete', function(client, text) {
//                    //alert("Copied text to clipboard:\n" + text);
//                    showNotification(text + ' copied...');
//                });

//            });
            

            var oSettings = oTable.fnSettings();
            totalRecords = oSettings.fnRecordsTotal();
            pageSize = oSettings._iDisplayLength;

            if(totalRecords == -1)
            {
                $().toastmessage('showToast',{sticky : true, text:'Oops, an error occurred while loading the keywords for this job.  Please try again.', type: 'error', position : 'middle-center' });
            }

            //select all
            ResetSelectAllKeywords();

            
        }
    });
    
    
    //oTable.fnAdjustColumnSizing();

    $(window).bind('resize', function () {
        if(!$.browser.msie)
        {
            oTable.fnAdjustColumnSizing();
        }
    } );
}

function ShowSelectedKeywords()
{
    var countCheck = 0;

    $(".chkKeyword").each(function (){
        if($(this).is(':checked'))
        {                            
            countCheck++;
        }
    });

    if(parseInt(countCheck) > 0)
    {
        if(parseInt(countCheck) == pageSize || parseInt(countCheck) == totalRecords)
        {
            var checkboxAll = document.getElementById('chkAll');

            checkboxAll.checked = true; 

            CheckAllClicked();
        }
        else
        {
            $('#selectedKeywordsContainer').html(countCheck + ' keywords are selected');
            $('#selectedKeywordsContainer').show();
            $('#selectedKeywordsContainer').fadeTo('fast', 0.8);

            $('#selectAllContainer').hide();

            var checkboxAll = document.getElementById('chkAll');

            checkboxAll.checked = false; 
        }
    }
    else
    {
        $('#selectedKeywordsContainer').hide();
    }
}

function CheckAllClicked()
{
    if($('#chkAll').is(':checked'))
    {
        $('#selectAllContainer').show();
        $('#selectAllContainer').fadeTo('fast', 0.8);
        $('#selectedKeywordsContainer').hide();
    }
    else{                
        ResetSelectAllKeywords();                
    }

    $(".chkKeyword").each(function (){
            
            var checkboxAll = document.getElementById($(this).attr('id'));

            checkboxAll.checked = $('#chkAll').is(':checked');

            if($(this).is(':checked'))
            {
                $(this).parent().parent().addClass('rSelected');
            }
            else {
                if($(this).parent().parent().hasClass('rSelected'))
                {
                    $(this).parent().parent().removeClass('rSelected');
                }
            }

    });
}

function SelectAllKeywords()
{
    //var breakTag = '<br />';
    var breakTag =  ' ';

//    if(parseInt($(window).width()) > 1080)
//    {
//        breakTag = ' ';
//    }
    
    $('#selectAllContainer').html('All ' + totalRecords + ' keywords are selected.' + breakTag + '<a href="#" id="lnkClearSelection" onclick="return false;">Clear Selected Keywords</a>');

    $('#allKeywordsSelected').val('yes');

    $('#lnkClearSelection').bind('click', ClearSelectAllKeywords);
}

function ClearSelectAllKeywords()
{
    ResetSelectAllKeywords();

    //$(".chkKeyword").attr('checked', $('#chkAll').is(':checked'));

    $(".chkKeyword").each(function (){
        
        var checkboxAll = document.getElementById($(this).attr('id'));

        checkboxAll.checked = $('#chkAll').is(':checked');
        
        if($(this).is(':checked'))
        {                            
            $(this).parent().parent().addClass('rSelected');
        }
        else {
            if($(this).parent().parent().hasClass('rSelected'))
            {
                $(this).parent().parent().removeClass('rSelected');
            }
        }
    });
}

function ResetSelectAllKeywords()
{
       //var breakTag = '<br />';
    var breakTag = ' ';

//    if(parseInt($(window).width()) > 1080)
//    {
//        breakTag = ' ';
//    }

    //reset
    $('#selectAllContainer').hide();
    $('#selectedKeywordsContainer').hide();

    if(totalRecords < pageSize)
    {
        $('#selectAllContainer').html('All ' + totalRecords + ' keywords are selected.');
    }
    else {
        $('#selectAllContainer').html('All ' + pageSize + ' keywords are selected.' + breakTag + '<a href="#" id="lnkSelectAllKeywords" onclick="return false;">Select all ' + totalRecords + ' Keywords</a>');
        $('#lnkSelectAllKeywords').bind('click', SelectAllKeywords);
    }

    $('#allKeywordsSelected').val('');

    UnCheckSelectAll();
}

function UnCheckSelectAll()
{
    var checkboxAll = document.getElementById('chkAll');

    if(checkboxAll.checked == true)
    {
        checkboxAll.checked = false;                
    }    
}



function fadeIn(controlId) {
    if (controlId != '') {
        $('#' + controlId).fadeIn(1000);
        //$('#' + controlId).show();
    }
}
function fadeOut(controlId) {
    if (controlId != '') {
        //$('#' + controlId).fadeOut(300);
        $('#' + controlId).hide();
    }
}

function showHelp(helpTopic, helpTopicTitle)
{
    $('#helpTopic p').each(function (){
        $(this).hide();
    });

    $('span#helpTopicTitle').text(helpTopicTitle);
    $('p#' + helpTopic).show();
}

function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function showWarningJobCount(msg) {
    $().toastmessage('showToast', { sticky: true, text: msg, type: 'warning', position: 'middle-center' });
}


function initDashBoardDataTable(selectorName, processingScript) {

    var aoColumns = [];

    $(selectorName + ' thead th').each(function () {
        if ($(this).hasClass('no-sort')) {
            aoColumns.push({ "bSortable": false, "sWidth": $(this).width(), "sClass": $(this).attr('class') });
        } else {
            var sortType = "string";

            if ($(this).hasClass('numeric')) {
                sortType = "numeric"
            }

            aoColumns.push({ "sType": sortType, "sWidth": $(this).width(), "sClass": $(this).attr('class') });
        }
    });

   var oTable = $(selectorName).dataTable({
        "aoColumns": aoColumns,
        "bPaginate": false,
        "bJQueryUI": true,
        "sScrollY": 400,
        "bProcessing": true,
        "bFilter": false,
        "bServerSide": true,
        "bStateSave": true,
        "bAutoWidth": false,
        "bScrollInfinite": true,
        "sAjaxSource": processingScript,
        "oLanguage": {
            "sInfo": "Showing _START_ to _END_ of _TOTAL_ Keyword Pools",
            "sInfoEmpty": "Showing 0 to 0 of 0 Keyword Pools",
            "sZeroRecords": "No Keyword Pools",
            "sProcessing": "processing...",

        },
        "fnInitComplete": function () {
            // Toggle visibility on any heavyweight items to prevent the flash of unstyled content
                               
        },
        "fnFooterCallback": function () {
            // Toggle visibility on any heavyweight items to prevent the flash of unstyled content   
        },
        "fnDrawCallback": function () {          
            //shift click checkbox
            $('.shiftCheckBox').shiftcheckbox();
           
            //show row style
            $('.chkJob').bind("click", function () {
                    
                if($(this).is(':checked'))
                {
                    //alert('checked');
                    $(this).parent().parent().addClass('rSelected');
                }
                else {
                    if($(this).parent().parent().hasClass('rSelected'))
                    {
                        $(this).parent().parent().removeClass('rSelected');
                    }

                    //unselect the chkAll
                    var checkboxAllJob = document.getElementById('chkAll');

                     checkboxAllJob.checked = false;
                }
            });

            $("a.lnkRename").fancybox({ "onComplete": function () {$('#newTitle').focus().select();}, 'titleShow'	: false });

            $("a.lnkJobNotes").fancybox({ "onComplete": function () { showJobNotes(); }, 'titleShow'	: false, "onClosed"	: function() {  $('#txtJobNotes').val(''); }});

            //hide the page div
            $('#joblist-table_wrapper').children(':first-child').html('Keyword Pools');

            //show a welcome message if no jobs
            var oSettings = oTable.fnSettings();
            totalRecords = oSettings.fnRecordsTotal();

            if(totalRecords == -1)
            {
                $().toastmessage('showToast',{sticky : true, text:'Oops, an error occurred while trying to load your keyword pools.  Please try again.', type: 'error', position : 'middle-center' });
            }

            if(totalRecords == 0)
            {
                $().toastmessage('showToast',{sticky : true, text:'To get started, click on the "New Keyword Pool" tab (the one with the PLUS sign) to create a new Keyword Pool.', type: 'notice', position : 'top-center' });
            }

        }
    });
    
}

$(document).ready(function () {

    //Keyword List
    $('#lnkDownload').click(function () {

        $('#jsq').val(Math.floor(Math.random() * 11));
        document.downloadForm.submit();
    });

    $('#lnkClearM').click(function () {
        $('#keywordMasterList').html('');
        $('#keywordCountM').html('0 Keywords');
    });




    $('#lnkAddGAS').click(function () {

        showProcessingText('processing...', true);

        setTimeout(function () {

            var counter = parseInt($('#keywordCountM').html().replace(' Keywords', ''));

            var htmlToAppend = '';

            var exceeded5000 = false;

            $('#keywordIdeasGAS input:checked').each(function () {

                var currentId = $(this).attr('id');

                //check to see if this one is not already in the list
                var doesItExist = false;

                if ($('#m_' + currentId).length > 0) {
                    doesItExist = true;
                }

                if(counter < 5000)
                {
                    if (doesItExist == false) {

                        htmlToAppend = htmlToAppend + '<input type="checkbox" checked=\"checked\" value="' + $(this).val() + '" name="m_' + $(this).attr('id') + '" id="m_' + $(this).attr('id') + '" class="chkKeywordCheckList" />' +
                                                             '<span style="margin-left:8px;">' + $(this).val() + '</span><br />';

                        counter++;
                    }
                }
                else
                {
                    exceeded5000 = true;
                }
            });

            $('#keywordMasterList').html($('#keywordMasterList').html() + htmlToAppend);

            hideMask();

            $('#keywordCountM').html(counter + ' Keywords');

            if(exceeded5000 == true)
            {
                $().toastmessage('showToast',{sticky : true, text:'You have reached the maximum number of keywords that can be added to the keyword list, which is 5,000.  To continue, download the current keywords, and then clear the keyword list to add more.', type: 'warning', position : 'middle-center' });
            }

        }, 500);

    });

    $('#lnkClearGAS').click(function () {
        //reset html
        $('#keywordIdeasGAS').html('');

        $('#keywordCountGAS').html('0 Keywords');
    });

    
    //Google Product
    $('#lnkAddGP').click(function () {

        showProcessingText('processing...', true);

        setTimeout(function () {

            var counter = parseInt($('#keywordCountM').html().replace(' Keywords', ''));

            var htmlToAppend = '';

             var exceeded5000 = false;

            $('#keywordIdeasGP input:checked').each(function () {

                var currentId = $(this).attr('id');

                //check to see if this one is not already in the list
                var doesItExist = false;

                if ($('#m_' + currentId).length > 0) {
                    doesItExist = true;
                }

                if(counter < 5000)
                {
                    if (doesItExist == false) {

                        htmlToAppend = htmlToAppend + '<input type="checkbox" checked=\"checked\"  value="' + $(this).val() + '" name="m_' + $(this).attr('id') + '" id="m_' + $(this).attr('id') + '" class="chkKeywordCheckList" />' +
                                                             '<span style="margin-left:8px;">' + $(this).val() + '</span><br />';

                        counter++;
                    }
                }
                else
                {
                    exceeded5000 = true;
                }

            });

            $('#keywordMasterList').html($('#keywordMasterList').html() + htmlToAppend);

            hideMask();

            $('#keywordCountM').html(counter + ' Keywords');

            if(exceeded5000 == true)
            {
                $().toastmessage('showToast',{sticky : true, text:'You have reached the maximum number of keywords that can be added to the keyword list, which is 5,000.  To continue, download the current keywords, and then clear the keyword list to add more.', type: 'warning', position : 'middle-center' });
            }

        }, 500);

    });

    $('#lnkClearGP').click(function () {
        //reset html
        $('#keywordIdeasGP').html('');

        $('#keywordCountGP').html('0 Keywords');
    });

    //Amazon
    

    $('#lnkAddA').click(function () {

        showProcessingText('processing...', true);

        setTimeout(function () {

            var counter = parseInt($('#keywordCountM').html().replace(' Keywords', ''));

            var htmlToAppend = '';

            var exceeded5000 = false;

            $('#keywordIdeasAmazon input:checked').each(function () {

                var currentId = $(this).attr('id');

                //check to see if this one is not already in the list
                var doesItExist = false;

                if ($('#m_' + currentId).length > 0) {
                    doesItExist = true;
                }

                if(counter < 5000)
                {
                    if (doesItExist == false) {

                        htmlToAppend = htmlToAppend + '<input type="checkbox" checked=\"checked\" value="' + $(this).val() + '" name="m_' + $(this).attr('id') + '" id="m_' + $(this).attr('id') + '" class="chkKeywordCheckList" />' +
                                                             '<span style="margin-left:8px;">' + $(this).val() + '</span><br />';

                        counter++;
                    }
                }
                else
                {
                    exceeded5000 = true;
                }

            });

            $('#keywordMasterList').html($('#keywordMasterList').html() + htmlToAppend);

            hideMask();

            $('#keywordCountM').html(counter + ' Keywords');

            if(exceeded5000 == true)
            {
                $().toastmessage('showToast',{sticky : true, text:'You have reached the maximum number of keywords that can be added to the keyword list, which is 5,000.  To continue, download the current keywords, and then clear the keyword list to add more.', type: 'warning', position : 'middle-center' });
            }

        }, 500);

    });

    $('#lnkClearA').click(function () {
        //reset html
        $('#keywordIdeasAmazon').html('');

        $('#keywordCountA').html('0 Keywords');
    });
});

function showHelp(helpType) {

    if (helpType == 'GAS') {
        $().toastmessage('showToast', { sticky: true, text: 'Enter a keyword into the field provided and then click the "GO" button to get the keyword suggestions.<br /><br />You can try keywords like:<br /><br />how to *<br />how * baby<br />for * kids<br />* honey<br />help * heart burn<br /><br />Place the * (asterisk) where you want Google to fill in the blanks.', type: 'notice', position: 'middle-center' });
    }
    else if (helpType == 'GP') {
        $().toastmessage('showToast', { sticky: true, text: 'Enter a keyword or product into the field provided and then click the "GO" button to get the keyword suggestions.<br /><br />You can try keywords like:<br /><br />harley davidson<br />ice cream maker<br />car wash soap<br />kids toys', type: 'notice', position: 'middle-center' });
    }
    else if (helpType == 'Amazon') {
        $().toastmessage('showToast', { sticky: true, text: 'Enter a keyword or product into the field provided and then click the "GO" button to get the keyword suggestions.<br /><br />You can try keywords like:<br /><br />harley davidson<br />ice cream maker<br />car wash soap<br />kids toys', type: 'notice', position: 'middle-center' });
    }
    else if(helpType == 'Import')
    {
        $().toastmessage('showToast', { sticky: true, text: 'Download csv files (csv for excel or plain csv both work) from the Google Adwords Keyword Tool. Don’t forget to set results to exact match and configure the columns correctly: local and/or global monthly searches, advertiser competition, and approximate CPC.', type: 'notice', position: 'middle-center' });
    }
}
