//domain = 'http://saleawaywithme.geniiweb.com/';
domain = 'http://saleawaywithme.com/';

function filter_retailers()
{
    if($(this).text() == 'See all')
        all_value = 'yes';
    else  	all_value = 'no';
    selected_ids_value = '';
    $('#retailers input[type=checkbox]:checked').each(function() {
        selected_ids_value += ','+$(this).attr('value');
    });
    selected_ids_value = selected_ids_value.substr(1);

    //$('#retailers').html('<img src="'+domain+'images/ajax-loader.gif" id="loader" /> Loading retailers. Please wait!');
    $('#retailers').html('<img src="'+domain+'images/ajax-loader.gif" id="loader" /> Loading retailers. Please wait!');
    $.post('home/ajax_retailers/', {
        all:all_value,
        selected_ids:selected_ids_value
    }, function(data){
        $('#retailers').hide('fast');
        $('#retailers').html(data);
        $('#retailers').show('fast');
        select_retailers();
        if ($('#filter_retailers').text() == 'See all') {
            $('#filter_retailers').text('See featured');
            $('#retailers_text').text('All Retailers');
        }
        else {
            $('#filter_retailers').text('See all');
            $('#retailers_text').text('Featured Retailers');
        }
    });
}

function search_autocomplete() {
    if ($('.search_retailers').length > 0)
        $('.search_retailers').autocomplete(domain+"admin/search_retailers", {
            width: 200,
            selectFirst: false
        });
    if ($('.search_categories').length > 0)
        $('.search_categories').autocomplete(domain+"admin/search_categories", {
            width: 200,
            selectFirst: false
        });
}

function select_retailers() {
    retailers_selected_obj = $('input#retailers_selected');
    if (retailers_selected_obj.length == 0) return;
    $('input[type=checkbox][name="retailers[]"] :checked').each(function() {
        $(this).attr('checked', false);
    });
    arr_values = retailers_selected_obj.attr('value').split(',');
    for (i = 0; i < arr_values.length; i++)
        $('input[type=checkbox][name="retailers[]"][value='+arr_values[i]+']').attr('checked', 'true');
}

function select_categories() {
    categories_selected_obj = $('input#categories_selected');
    if (categories_selected_obj.length == 0) return;
    $('input[type=checkbox][name="categories[]"]:checked').each(function() {
        $(this).attr('checked', false);
    });
    arr_values = categories_selected_obj.attr('value').split(',');
    for (i = 0; i < arr_values.length; i++)
        $('input[type=checkbox][name="categories[]"][value='+arr_values[i]+']').attr('checked', 'true');
}

function reset_all() {
    //select_retailers();
    select_categories();
}

function select_all() {
    $('#send_emails input[type=checkbox]').each(function() {
        $(this).attr('checked', true);
    });
}

function select_none() {
    $('#send_emails input[type=checkbox]').each(function() {
        $(this).attr('checked', false);
    });
}

function ask_delete(link) {
    if (window.confirm('Are you sure you want to delete this item?'))
        document.location = link;
}

function send_newsletter() {
    send_next_email();
}

function send_next_email()
{
    parent_val = $('#send_emails input[type=checkbox]:checked:first').parent();
    if (parent_val.length == 0)
    {
        alert('All emails have been sent!');
        $('del').each(function() {
            $(this).after($(this).html());
            $(this).remove();
        });
        $('.currently_sending').remove();
        $.get(domain+'admin/ajax_last_email');
        return;
    }

    // get the newsletter subject
    subject_val = '';
    if ($('.form_item input[name=subject]').length > 0)
        subject_val = $('.form_item input[name=subject]').attr('value');
    if (subject_val == '')
    {
        alert('Please set the newsletter subject!');
        $('del').each(function() {
            $(this).after($(this).html());
            $(this).remove();
        });
        $('.currently_sending').remove();
        return;
    }

    email_address = parent_val.find('.the_email').text();

    if ($('#the_subject').length > 0)
        post_subject = $('#the_subject').attr('value').replace(/(<([^>]+)>)/ig,"");
    else 	post_subject = '';
    $('#the_subject').after('<div id="subject_wrapper">' + post_subject + '</div>');
    $('#the_subject').remove();

    if (parent_val.find('.currently_sending').length == 0)
        parent_val.find('input[type=checkbox]').after('<span style="color: green" class="currently_sending">SENDING.. </span>');

    try{
        ajax_url = domain+'admin/ajax_send_email/';
        if (document.location.href.indexOf('debug') >= 0) ajax_url += 'debug/';
        //$.post(ajax_send_email, {email: email_address, subject: subject_val}, function(response){
        $.post(ajax_url, {
            email: email_address,
            subject: subject_val
        }, function(response){
            message_val = 'SENT!';
            if (response['error'])
                message_val = response['error_message'];

            parent_val.find('.currently_sending').text(message_val);
            parent_val.find('.currently_sending').css('color', 'red');
            parent_val.html('<del>'+parent_val.html()+'</del>');
            parent_val.find('input[type=checkbox]').attr('checked', false);

            send_next_email();
        }, 'json');
    }
    catch(ex) {
        parent_val.find('.currently_sending').remove();
        alert('There was a problem sending the emails!');
    }
}

function forms_validation() {
    error_message = 'Please complete all mandatory fields.';

    forms = [];
    forms['frm_forgot_password'] = 'email';
    forms['frm_contact_us'] = 'subject,message';
    forms['frm_login'] = 'email,password';
    forms['frm_register'] = 'email';
    forms['frm_unsubscribe'] = 'email';
    forms['frm_add_offer'] = 'name,link,merchant,new_price,date,category';
    forms['frm_add_category'] = 'name';
    forms['frm_add_retailer'] = 'name';
    forms['frm_import_csv'] = 'csv';
    forms['frm_template_text'] = 'template';


    // associate the validation functions
    for (form_id in forms)
        if ($('#'+form_id).length > 0)
            $('#'+form_id).submit(function()
            {
                form_id = $(this).attr('id');
                fields = forms[form_id].split(',');
                found_all_values = true;
                for (key in fields)
                {
                    field_name = fields[key].trim();
                    field_names = [];
                    field_names.push('input[name="' + field_name + '"]');
                    field_names.push('textarea[name="' + field_name + '"]');
                    field_names.push('select[name="' + field_name + '"]');

                    value_found = false;
                    for (key_field_names in field_names)
                    {
                        input_field = $(this).find(field_names[key_field_names]);
                        if (input_field.length > 0) {
                            if (input_field.attr('value').trim() != '') value_found = true;
                            else input_field.focus();
                            break;
                        }
                    }
                    if ( ! value_found) {
                        found_all_values = false;
                        break;
                    }
                }
                if ( ! found_all_values)
                {
                    alert(error_message);
                    return false;
                }
                return true;
            });
}

function select_boxes(tag_id) {
    $(tag_id + ' input[type=checkbox]').attr('checked', true);
    elem = $('#retailers').find('button:first');
    elem.removeAttr("disabled");
    if (document.location.href.indexOf('sale_alerts')) $.get(domain + 'home/select_retailers/all');
}
function select_boxes_featured(tag_id) {
    $(tag_id + ' input[type=checkbox]').attr('checked', true);
    elem = $('#retailers').find('button:first');
    elem.removeAttr("disabled");
    if (document.location.href.indexOf('sale_alerts'))
        $.get(domain + 'home/select_retailers/all_featured');
}
function deselect_boxes(tag_id) {
    $(tag_id + ' input[type=checkbox]').attr('checked', false);
    elem = $('#retailers').find('button:first');
    elem.attr("disabled", true);
    if (document.location.href.indexOf('sale_alerts')) $.get(domain + 'home/deselect_retailers/all');
}

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}

function order_by(orderby, direction) {
    $('table#manage_items').parent().before('<form id="frm_manage_items" action="" method="post"><input type="hidden" name="orderby" value="'+orderby+'" /><input type="hidden" name="direction" value="'+direction+'" /></form>');
    $('#frm_manage_items').submit();
}

function add_coupon()
{
    if ($('#coupons_container').length == 0) return;
    $.getJSON(domain + 'retailers/ajax_new_coupon', {}, function(data) {
        if (data['error']) { 
            alert(data['error_message']); return;
        }
        $('#coupons_container').prepend(data['html']);
        $('#frm_add_retailer input[name=expires_'+data['coupon_id']+']')
        .datepicker({
            dateFormat: 'yy-mm-dd'
        });
    });
}

function remove_coupon(coupon_id)
{
    if (coupon_id == 0)
    {
        $('#coupon_'+coupon_id).remove();
        return;
    }

    $.getJSON(domain+'retailers/ajax_remove_coupon/'+coupon_id, {}, function(data) {
        if (data['error']) { 
            alert(data['error_message']); return;
        }
        $('#coupon_'+coupon_id).remove();
    });
}

function generate_code(coupon_id)
{
    $('#coupons_container input[name=code_'+coupon_id+']').attr('value', randomString(5));
}

function randomString(len)
{
    //var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
    var string_length = len;
    var randomstring = '';
    for (var i=0; i<string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum,rnum+1);
    }
    return randomstring;
}


function save_brands() {
    val_brands = '';
    $('input[type=checkbox][name=brands[]]:checked').each(function() {
        val_brands += $(this).val() + ',';
    });
    val_stores = '';
    $('input[type=checkbox][name=stores[]]:checked').each(function() {
        val_stores += $(this).val() + ',';
    });
    $.post(domain + 'retailers/ajax_save_brands', {brands: val_brands,stores: val_stores}, function(data) {
        if (data['error']) { alert(data['error_message']); return; }
        alert('Brands/Stores saved!');
    });

}