$(document).ready(function(){
	/*
	// Pre-Load Form Inputs with Values
	// http://www.ajaxblender.com/howto-add-hints-form-auto-focus-using-javascript.html
	$('.auto-focus:first').focus();
	//  Initialize auto-hint fields
	$('input.auto-hint, textarea.auto-hint').focus(function(){
		if($(this).val() == $(this).attr('title')){ 
			$(this).val('');
			$(this).removeClass('auto-hint');
		}
	});
	$('input.auto-hint, textarea.auto-hint').blur(function(){
		if($(this).val() == '' && $(this).attr('title') != ''){ 
			$(this).val($(this).attr('title'));
			$(this).addClass('auto-hint'); 
		}
	});
	$('input.auto-hint, textarea.auto-hint').each(function(){
		if($(this).attr('title') == ''){ return; }
		if($(this).val() == ''){ $(this).val($(this).attr('title')); }
		else { $(this).removeClass('auto-hint'); } 
	});
	*/

	// -----
	// Help Link Popup to FancyBox
	$("#documentationlink").fancybox({
		'width'				: '100%',
		'height'			: '100%',
		'autoScale'			: false,
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'				: 'iframe',
		'autoDimensions'	: false
	});

	// -----
	// Help Link Popup to FancyBox
	$("#nav-support-link").fancybox({
		'width'				: '100%',
		'height'			: '100%',
		'autoScale'			: false,
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'				: 'iframe',
		'autoDimensions'	: false
	});

	// -----
	// Help Links Popup to FancyBox
	$(".left-nav-doc-lightbox").fancybox({
		'width'				: '100%',
		'height'			: '100%',
		'autoScale'			: false,
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'				: 'iframe',
		'autoDimensions'	: false
	});

	// -----
	// Help Links Popup to FancyBox
	$(".right-content-doc-lightbox").fancybox({
		'width'				: '100%',
		'height'			: '100%',
		'autoScale'			: false,
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'				: 'iframe',
		'autoDimensions'	: false
	});


    // SelectBox init
    // Pages that modify select boxes need to call
    //  $("SELECT").selectBox('destroy');
    //  $("SELECT").selectBox();
    // after doing so
    $("SELECT").selectBox();

	/*
    // prettyCheckboxes initialization
    $('input[type=checkbox],input[type=radio]').prettyCheckboxes();
	*/

	// Tipsy Tooltip init
    $('.show-tooltip').tipsy({
        gravity: 's',
        delayIn: 1000,
        delayOut: 250, 
        fade: true,
		opacity:0.90
    });
});



/*
// jStyle lite initialization
$(function(){
	$('body').jStyle();
});
*/

// Cookie setter
function SetCookie(name, value, days) {
    var today = new Date();
    var expire = new Date();

    if (days == null || days == 0) {
         days = 1;
    }

    expire.setTime(today.getTime() + 3600000 * 24 * days);

    document.cookie = name + "=" + escape(value) + ";expires=" + expire.toGMTString();
}


// Sort an "associative array" key asc
function obj_key_sort(obj) {
    var keys = new Array();
    var sorted_obj = new Array();

    for (var i in obj) {
        if (obj.hasOwnProperty(i)) {
            keys.push(i);
        }
    }

    keys.sort();

    for (var i in keys) {
        sorted_obj[keys[i]] = obj[keys[i]];
    }

    return sorted_obj;
}

// Confirm text isn't more than N lines long, broken on \n
// If the text is too long, return the shortened version
function too_many_lines(text, max_lines) {
    var lines_arr = text.split("\n");

    if (lines_arr.length > max_lines) {
        return lines_arr.slice(0, max_lines).join("\n");
    }

    return false;
}

// Confirm there are no duplicate lines in the provided text,
// broken on \n
function no_dup_lines(text) {
    var lines_arr = text.split("\n");
    lines_arr.forEach( function (v, i) {
        lines_arr[i] = jQuery.trim(v).toLowerCase();
    } );

    lines_arr.sort();

    var last_line = false;
    for (var i=0; i<lines_arr.length; i++) {
        if (!last_line) {
            last_line = lines_arr[i];
        }
        else {
            if (lines_arr[i] == last_line) {
                return false;
            }

            last_line = lines_arr[i];
        }
    }

    return true;
}

// Validate a value based on a passed regex
// If match_regex is true, text must match on regex
// If match_regex is false, text must fail on regex
function validate_by_regex(text, regex, match_regex) {
    var regex_o = new RegExp(regex);
    var matches = regex_o.exec(text);

    if (match_regex) {
        if (matches == null) {
            return false;
        }

        return true;
    }
    else {
        if (matches == null) {
            return true;
        }

        return false;
    }
}

// Update URL qualification status including toggling button states appropriately
function update_url_q_status(url_id, campaign_id, selected_id, rownum, selected_class) {
    // If the pressed button was already "pressed", we're removing an existing status, not updating/inserting one
    var deselect_pressed = selected_class.match(/ selected/);

    var q_status = /-([^-]+)-\d+$/.exec(selected_id)[1];
    var q_status_id = false;

    if (q_status == "qualified") {
        q_status_id = 1;
    }
    else if (q_status == "furtherreview") {
        q_status_id = 2;
    }
    else if (q_status == "rejected") {
        q_status_id = 3;
    }

    if (!q_status_id) {
        var msg = 'Qualification status update failed: Cannot determine qualification status ID';

        $( "#dialog-alert" ).html(msg).dialog({
            title: 'An error occurred',
            resizable: false,
            modal: true,
            buttons: {
                Ok: function() {
                    $( this ).dialog( "close" );
                }
            }
        });

        return;
    }

    var button_ids = new Array();
    button_ids.push('status-q-qualified-' + rownum);
    button_ids.push('status-q-furtherreview-' + rownum);
    button_ids.push('status-q-rejected-' + rownum);

    var ajax_url = './sites/default/files/app/v4/data-processing/processing-update-url-q-status.php';

    var r = $.ajax({
        url: ajax_url,
        type: "POST",
        data: {
            "url_id": url_id,
            "q_status_id": q_status_id,
            "campaign_id": campaign_id,
            "unset_status": deselect_pressed
        },
        dataType: 'json'
    });

    r.done(function() {
        var response = $.parseJSON(r.responseText);
        if (!response.success) {
            $( "#dialog-alert" ).html(response.errmsg).dialog({
                title: 'An error occurred',
                resizable: false,
                modal: true,
                buttons: {
                    Ok: function() {
                        $( this ).dialog( "close" );
                    }
                }
            });
        }
        else {
            $('#' + selected_id).addClass("selected");

            for (var i=0; i<button_ids.length; i++) {
                if (button_ids[i] != selected_id || deselect_pressed) {
                    $('#' + button_ids[i]).removeClass("selected");
                }
            }
        }
    });

    r.fail(function(jqXHR, textStatus) {
        $( "#dialog-alert" ).html(jqXHR.status + ': ' + jqXHR.statusText).dialog({
            title: 'An error occurred',
            resizable: false,
            modal: true,
            buttons: {
                Ok: function() {
                    $( this ).dialog( "close" );
                }
            }
        });
    });
}

function mysql_timestamp_to_browser_timezone(mysql_timestamp) {
    var this_date_parts = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/.exec(mysql_timestamp);
    this_year = this_date_parts[1];
    this_month = this_date_parts[2];
    this_day = this_date_parts[3];
    this_hours = this_date_parts[4];
    this_minutes = this_date_parts[5];
    this_seconds = this_date_parts[6];

    var this_date = new Date(this_year, this_month, this_day, this_hours, this_minutes, this_seconds, 0);
    var local_gmt_offset_ms = this_date.getTimezoneOffset() * 60000;
    var local_date = new Date(this_date.valueOf() - local_gmt_offset_ms);
    var local_date_year = local_date.getFullYear().toString();
//    var local_date_month = (local_date.getMonth() + 1).toString();
    var local_date_month = (local_date.getMonth()).toString();
    var local_date_date = local_date.getDate().toString();
    var local_date_time = local_date.toLocaleTimeString();

    if (local_date_month.length < 2) {
        local_date_month = '0' + local_date_month;
    }

    if (local_date_date.length < 2) {
        local_date_date = '0' + local_date_date;
    }

    var local_date_str = local_date_year + '-' + local_date_month + '-' + local_date_date + ' ' + local_date_time;

    return local_date_str;
}

var db_not_ready_msg = 'Your Ontolo Toolset account is currently being setup, which usually takes a couple minutes.<br><br>';
db_not_ready_msg += 'In the meantime, we recommend that you head on over to the <a href="http://ontolo.com/quick-start-guide">Quick Start Guide</a> ';
db_not_ready_msg += 'to learn how to best setup your account for the most relevant and valuable link prospects.';

function is_project_db_ready() {
    var ajax_url = './sites/default/files/app/v4/data-processing/processing-is-project-db-ready.php';
    var r = $.ajax({
        url: ajax_url,
        type: "POST",
        dataType: 'json',
        async: false
    });

    var response = $.parseJSON(r.responseText);
    if (!response.success) {
        return [false, response.errmsg];
    }
    else {
        return [true, ''];
    }
}

