/**
 * Press Release Grader Client Side Library
 *
 * Adapted from Mawi's client side library for WSG
 */
(function($){

    var messages = ["Dude, where's my leads. -- Jesse","What gets us into trouble is not what we don't know.  It's what we know for sure that just ain't so. -Mark Twain","If you wanted it to convert, you shoulda put a HubSpot form on it.","Are those extra leads in your pocket, or did you buy HubSpot large?","Ding! You are now free to get found by more leads.","With a name like HubSpot, it has to be good.","You want the leads? You can't handle the leads! -- Colonel Jessup","IMMA let you finish, but HubSpot has the best marketing software EVAR!","HubSpot: so easy a salesperson could do it.","In order to get everything in HubSpot, you'd have to eat 20 servings of other marketing software products.","I want to be one less bad marketer.","I feel the need, the need for leads. -- Maverick & Goose","1 Biiiiiiiiiiiiiiiilion leads! -- Dr. Evil","PPC is Temporary, SEO is forever.","HubSpot Software: $250, Monthly Internet Connection: $60, Increasing Sales: Priceless.","Confuscious say, I see large funnel in your future.","Marketer Tested, CEO Approved.","HubSpot, We're here to pump, you up. -- Hans and Franz","Toto, I've got a feeling we're not traditional marketing anymore.","Generate Leads with HubSpot, you will. -- Yoda","If high lead flow lasts longer than four hours contact HubSpot software support.","You've Got Leads -- AOL","If you have more money than brains, you should focus on outbound marketing. If you have more brains than money, you should focus on inbound marketing. -Guy Kawasaki","Leads are good. -- Gordon Gekko","Maybe they're born with it, maybe it's HubSpot.","By the time there is a case study in your specific industry, it's going to be way too late for you to catch up. -Seth Godin","Either write something worth reading about or do something worth writing about. -Ben Franklin"];
    messageMachine = {
        panel: null,
        init: function(hostDomain){
            ScrollToElement(document.getElementById("header"));
            var id = "#dialog";
            var maskHeight = $(document).height();
            var maskWidth = $(window).width();
            $('#mask').css({
                'width': maskWidth,
                'height': maskHeight
            });
            $('#mask').fadeTo(100, 0.55,function(){$('#mask').show();});
            var winH = $(window).height();
            var winW = $(window).width();
            $(id).css('top', winH / 2- $(id).width() / 2 );
            $(id).css('left', winW / 2 - $(id).width() / 2);
            $(id).fadeIn(100);
            /*$.ajax({
                type: 'GET',
                url: hostDomain + '/waiting_messages',
                dataType: 'json',
                success: function(data){
		    var messages = data.messages;
                    setInterval(function(){
                        var message = messages.shift();
                        $("#waiting_message").html(message);
                        messages.push(message);
                    }, 8000);
                },
                data: {},
                asynch: false
            });*/
	    setInterval(function(){
		var message = messages.shift();
		$("#waiting_message").html(message);
		messages.push(message);
	    }, 8000);
        },
        hide: function(){
            $('#mask, .window').hide();
        }
    }
    
    var grader = window.grader = window.grader || {}, 
	prg = grader.prg = grader.prg || {},
	generator = prg.reportGenerator = prg.reportGenerator || {};
    
    generator.userToken = "";
    generator.ipAddress = "";
    generator.finishCallback = null;
    generator.callBackUrl = "";
    generator.progressHandlerId = null;
    generator.checkProgressInterval = 2000;
    generator.inProgress = false;
    generator.inActiveAjaxCall = false;
    generator.hostDomain = "http://pressrelease.grader.com";
    
    generator.init = function(ipAddress, callBackUrl, hostDomain) {
        generator.ipAddress = ipAddress;
        generator.callBackUrl = callBackUrl;
        generator.hostDomain = hostDomain;
        $.ajaxSetup({
            timeout: 30000
        });
        $(document).ajaxError(function(event, request, settings, thrownError){
            var ajax_div = $('#ajax');
            ajax_div.hide();

            generator.inActiveAjaxCall = false;
            logSafely("Ajax call failed");
            logSafely("Request: " + request);
            logSafely("Event: " + event);
            logSafely("Error: " + thrownError);
            logSafely("Settings: " + settings);
            generator.finished();
            generator.callFinishCallBack();
            messageMachine.hide();
            
            var error_html = '<div class="col1">'+"\n"+'                            <div class="pad">'+"\n"+'                                <div class="form">'+"\n"+'                                    <div class="results">'+"\n"+'                                        <div class="message alert">'+"\n"+'                                            <p class="error">'+"\n"+'Sorry, an unexpected error has occurred. Please try resubmitting your content <a href="/">here.</a>'+"\n"+'                                            </p>'+"\n"+'                                        </div>'+"\n"+'                                    </div>'+"\n"+'                                </div>'+"\n"+'                            </div>'+"\n"+'                        </div><!-- END div.col1 -->';
            ajax_div.html(error_html);
            ajax_div.fadeIn('fast');

        });
        
        $(document).ajaxStart(function(){
            generator.inActiveAjaxCall = true;
        });
        $(document).ajaxComplete(function(){
            generator.inActiveAjaxCall = false;
        });
    }
    
    generator.start = function(finishCallback){
	
        if (generator.inActiveAjaxCall) {
            logSafely("generator.inActiveAjaxCall");
            generator.callFinishCallBack();
            return;
        }
        if (generator.inProgress) {
            logSafely("generator.inProgress");
            generator.callFinishCallBack();
            return;
        }

        var currentUserToken = ReadCookie('hubspotutk');
        if (currentUserToken == '' || currentUserToken == 'undefined') {
        
            currentUserToken = "";
            for (var i = 0; i < 32; i++) {
                currentUserToken += Math.floor(Math.random() * 0xF).toString(0xF);
            }
        }
        
        generator.userToken = currentUserToken;
        generator.finishCallback = finishCallback;

        var postedData = {
            text: tinyMCE.get('text').getContent(),
            company_name: $('#company_name').val(),
            company_web: $('#company_web').val(),
            email: $('#email').val(),
            optin: $('#optin').val(),
            user_token: generator.userToken,
            ip_address: generator.ipAddress
        };

        generator.inProgress = true;
        generator.showProgressPopUp();
        
        ajaxUrl = generator.callBackUrl;
/*
        $.post(ajaxUrl, postedData, function(data) {
//            document.clear();
//            document.write(data);
            var ajax_div = $('#ajax');
            ajax_div.fadeOut('fast');
            ajax_div.hide();
            ajax_div.html(data);
            generator.finished();
            ajax_div.fadeIn();
        })
	*/
    }
    
    generator.validResponse = function(data){
        return (data != null);
    };

    generator.started = function(){
        generator.inProgress = true;
    };
    generator.finished = function(){
            generator.inProgress = false;
            generator.callFinishCallBack();
            messageMachine.hide();
    };
    generator.callFinishCallBack = function(){
        if (generator.finishCallback != null) {
            generator.finishCallback();
        }
    };
    
    generator.showProgressPopUp = function(){
        messageMachine.init(generator.hostDomain);
    }
})(jQuery);