function fieldEvent(event, text) {
    target = event.currentTarget || event.srcElement;
    if (event.type == 'focus' && target.value == text) {
        target.className = 'fieldBlack';
        target.value = '';
    } else if (event.type == 'blur' && target.value == '') {
        target.className = 'fieldGray';
        target.value = text;
    }
}

function toggleSection(checkbox, section) {
    if (checkbox.checked) {
        document.getElementById(section).style.display = 'block';
    } else {
        document.getElementById(section).style.display = 'none';
    }
}

function displaySection(element, section, show) {
    if (element.checked) {
        if(show)
            document.getElementById(section).style.display = 'block';
        else
            document.getElementById(section).style.display = 'none';
    }
}

function update_link_text(check_object_id, link_object_id, link_text_empty, link_text_not_empty)
{
    if (!check_object_id || !link_object_id || !link_text_empty || !link_text_not_empty) {
        return false;
    }
    var cc = document.getElementById(check_object_id);
    var lt = document.getElementById(link_object_id);
    if (!cc || !lt) {
        return false;
    }

    if ("" == trim(cc.innerHTML)) {
        lt.innerHTML = js_html_entities(link_text_empty);
    } else {
        lt.innerHTML = js_html_entities(link_text_not_empty);
    }

    return true;
}

function js_html_entities(s)
{
    if (!s) {
        return "";
    }
    var st = new String();
    for(var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if (trans_table[c]) {
            st += trans_table[c];
        } else {
            st += c;
        }
    }

    return st;
}

function js_nl2br(s)
{
    if (!s) {
        return "";
    }
    s = s.replace(/\\n/g, "<br />");
    return s;
}

/* ================ VARIOUS LINKS AND CODES FUNCTIONS ================ */

function create_online_link_input() {
    if (document.getElementById('deal[Online][link]')) {
        return true;
    }

    var class_name = 'fieldGray';
    if (OnlineLink != ONLINE_LINK_DEFAULT && OnlineLink != "") {
        class_name = 'fieldBlack';
    } else {
        OnlineLink = ONLINE_LINK_DEFAULT;
    }

    var html_cont = '<table class="reportDeal" cellspacing="0">'
              +'<tbody><tr>'
              +'    <td class="column">Link</td>'
              +'    <td><input type="text"  VALUE="'
              + OnlineLink + '" MAXLENGTH="4000" ONBLUR="fieldEvent(event, \''+ONLINE_LINK_DEFAULT+'\');" '
              +' ONFOCUS="fieldEvent(event, \''+ONLINE_LINK_DEFAULT+'\');" STYLE="width:380px" CLASS="'+class_name+'" NAME="deal[Online][link]" ID="deal[Online][link]" STYLE="width:380px" /></td>'
              +'    </tr>'
              +' </tbody></table>';

    var div_box = document.getElementById('address');
    if (!div_box) {
        return false;
    }

    div_box.innerHTML = html_cont;
    div_box.style.display = 'block';

    return true;
}

function delete_online_link_input() {
    if (!document.getElementById('deal[Online][link]')) {
        return true;
    }

    OnlineLink = document.getElementById('deal[Online][link]').value;
    var div_box = document.getElementById('address');
    if (!div_box) {
        return false;
    }
    div_box.innerHTML = '';
    div_box.style.display = 'none';
    return true;
}

var last_mail_in_rebate_id = -1;

function create_mail_in_rebate(url_fillin, description_fillin)
{
    last_mail_in_rebate_id++;

    var class_name = 'fieldGray';

    if (url_fillin && url_fillin != MIR_LINK_DEFAULT && url_fillin != "") {
        class_name = 'fieldBlack';
    } else {
        url_fillin = MIR_LINK_DEFAULT;
    }

    var descr_class = 'fieldGray';
    if (description_fillin && description_fillin != REBATE_DETAILS_DEFAULT && description_fillin != "") {
        descr_class = 'fieldBlack';
    } else {
        description_fillin = REBATE_DETAILS_DEFAULT;
    }

    var html_cont =  '<table class="reportDeal" cellspacing="0">' +
            '<tbody>'+
            '<tr>'+
            '   <td class="column">&nbsp;</td>'+
            '   <td>'+
            '       <input type="text"  VALUE="'+ url_fillin + '" MAXLENGTH="4000" '+
            '           ONBLUR="fieldEvent(event, \''+MIR_LINK_DEFAULT+'\');" ONFOCUS="fieldEvent(event, \''+MIR_LINK_DEFAULT+'\');" '+
            '           STYLE="width: 190px;" CLASS="'+class_name+'" NAME="deal[Rebates]['+last_mail_in_rebate_id+'][link]"'+
            '           ID="deal[Rebates]['+last_mail_in_rebate_id+'][link]" />'+
            '       <input type="text" style="width: 270px; margin: 0 5px;" class="'+descr_class+'" value="'+description_fillin+'" '+
            '           NAME="deal[Rebates]['+last_mail_in_rebate_id+'][details]" ID="deal[Rebates]['+last_mail_in_rebate_id+'][details]" '+
            '           onfocus="fieldEvent(event, \''+REBATE_DETAILS_DEFAULT+'\');" onblur="fieldEvent(event, \''+REBATE_DETAILS_DEFAULT+'\');" />' +
            '       <a href="#" onclick="remove_mail_in_rebate('+last_mail_in_rebate_id+'); return false;">remove</a>'+
            '   </td>'+
            '</tr>'+
            '</tbody>'+
            '</table>';

    var mirlink_div = document.getElementById("mirlink");
    if (!mirlink_div) {
        return false;
    }

    var mi = document.createElement('div');
    mi.id = 'mir_url_' + last_mail_in_rebate_id;
    mi.innerHTML = html_cont;

    mirlink_div.appendChild(mi);

    update_link_text("mirlink", "add_printable_rebate_text", "Add a link to a printable rebate form", "Add a link to another printable rebate form");

    return true;
}

function remove_mail_in_rebate(mir_id)
{
    var mir_block = document.getElementById('mir_url_' + mir_id);

    if (!mir_block || !mir_block.parentNode) {
        return false;
    }

    mir_block.parentNode.removeChild(mir_block);

    update_link_text("mirlink", "add_printable_rebate_text", "Add a link to a printable rebate form", "Add a link to another printable rebate form");

    return true;
}


/* =================== VALIDATION AND FORM SUBMITTAL FUNCTIONS =================== */

var error_message = "";
var init_error_message = "The following error(s) occured:\n";

function trim(str_v)
{
    if (!str_v || null == str_v) {
        return str_v;
    }

    str_v = str_v.replace(/^\s+/, "");
    str_v = str_v.replace(/\s+$/, "");

    return str_v;
}


function check_submit_form() {
    if (!validate_fields()) {
        return false;
    }

    var inputs = document.getElementsByTagName('input');
    for (i=0; i < inputs.length; i++) {
        if (inputs[i].onfocus) {
            var re = /['"]([^'"]+)['"]/;
            var match_re = re.exec(inputs[i].onfocus.toString());
            var text = null;
            if (match_re && match_re[1]) {
                text = match_re[1];
            }
            if (text && (inputs[i].className == 'fieldGray' || inputs[i].value == text)) {
                inputs[i].value = '';
            }
        }
    }

    return true;
}


function get_element_value(elem_id)
{
    var elem_box = document.getElementById(elem_id);
    if (!elem_box) {
        if (!document.forms["deal_form"]) {
            return null;
        }
        elem_box = document.forms["deal_form"].elements[elem_id];
        if (!elem_box) {
            return null;
        }
    }

    type = elem_box.type;
    if (!type) {
        type = "text";
    }

    /* might be a checkbox */
    if ("checkbox" == type || "radio" == type) {
        return elem_box.checked;
    }

    /* might be a radio button */
    if (type.indexOf("select") >= 0) {
        return elem_box.options[elem_box.selectedIndex].value;
    }

    /* might be an input or a textarea. */
    if (!elem_box.value) {
        return null;
    }

    if (!elem_box.onfocus) {
        return trim(elem_box.value);
    }

    var re = /['"]([^'"]+)['"]/;
    var match_re = re.exec(elem_box.onfocus.toString());
    if (!match_re || !match_re[1]) {
        return trim(elem_box.value);
    }

    var text = match_re[1];
    if (text && (elem_box.className == 'fieldGray' || elem_box.value == text)) {
        /* element has the default value */
        return "";
    }

    return trim(elem_box.value);
}

function is_empty_field(elem_id)
{
    var field_value = get_element_value(elem_id);

    if (null == field_value || "" == field_value) {
        return true;
    }

    return false;
}

function is_numeric_field(elem_id, positive)
{
    var field_value = get_element_value(elem_id);
    if (null == field_value || "" == field_value) {
        return true; //edge case to protect against double reporting of invalid field
    }

    field_value = strip_commas(field_value);
    field_value = strip_percent(field_value);

    if (parseFloat(field_value) != field_value) {
        return false;
    }

    if (true == positive && parseFloat(field_value) < 0.0) {
        return false;
    }

    return true;
}

function is_valid_percent_field(elem_id)
{
    if (!is_numeric_field(elem_id), true) {
        return false;
    }

    var field_value = get_element_value(elem_id);
    if (0 > field_value || 100 < field_value) {
        return false;
    }

    return true;
}


function check_deal_categories_selected( categories_parent_element )
{
    var inputs = categories_parent_element.getElementsByTagName( 'input' );
    for ( var i = 0; i < inputs.length; i++ )
    {
            if ( inputs[i].checked )
                return true;
    }
    
    return false;
}

function focus_required_field(elem_id)
{
    var elem_box = document.getElementById(elem_id);
    if (!elem_box) {
        return false;
    }

    elem_box.focus();
}

function set_required_field(elem_descr, elem_type)
{
    var to_add = "";
    if ("empty" == elem_type) {
        to_add = "- " + elem_descr + " must be entered to post or revise a deal.\n";
    } else if ("numeric" == elem_type) {
        to_add = "- Enter a number for " + elem_descr + ".\n";
    } else if ("positive numeric" == elem_type) {
        to_add = "- Enter a positive number for " + elem_descr + ".\n";
    } else if ("percent" == elem_type) {
        to_add = "- Enter a positive number 100 or less for " + elem_descr + ".\n";
    } else if ( "checked" == elem_type ) {
        to_add = "- At least one " + elem_descr + " must be checked.\n";
    }
    if (error_message.indexOf(to_add) >= 0) {
        return;
    }
    error_message += to_add;
}

function validate_fields()
{
    var required_fields = new Array(
            {"name" : "deal[Title]", "descr" : "Deal summary"}
    );

    var numeric_fields = new Array();
    var percentage_limited_fields = new Array();

    var validate_ok = true;

    error_message = init_error_message;

    var first_invalid_field = "";

    for(var i = 0; i < required_fields.length; i++) {
        if (is_empty_field(required_fields[i]["name"])) {
            set_required_field(required_fields[i]["descr"], "empty");
            if ("" == first_invalid_field) {
                first_invalid_field = required_fields[i]["name"];
            }
            validate_ok = false;
        }
    }
    if ( !check_deal_categories_selected( document.getElementById( 'categories_select_holder' ) ) )
    {
        set_required_field( 'category', 'checked' );
        validate_ok = false;
    }
    
    for(var i = 0; i < numeric_fields.length; i++) {
        if (!is_numeric_field(numeric_fields[i]["name"], numeric_fields[i]["positive"])) {
            set_required_field(numeric_fields[i]["descr"], (true == numeric_fields[i]["positive"] ? "positive ":"") + "numeric");
            if ("" == first_invalid_field) {
                first_invalid_field = numeric_fields[i]["name"];
            }
            validate_ok = false;
        }
    }

    for(var i = 0; i < percentage_limited_fields.length; i++) {
        if (!is_valid_percent_field(percentage_limited_fields[i]["name"])) {
            set_required_field(percentage_limited_fields[i]["descr"], "percent");
            if ("" == first_invalid_field) {
                first_invalid_field = percentage_limited_fields[i]["name"];
            }
            validate_ok = false;
        }
    }

    if ("" != first_invalid_field) {
        focus_required_field(first_invalid_field);
    }

    if ( document.getElementById("method_coupon").checked ) {
        if (document.getElementById("deal[Coupons][0][code]").className == 'fieldGray') {
            error_message  += "The Coupon type requires the coupon field completed.\n"
            validate_ok = false;
        }
    }

    if ( !(document.getElementById("method_coupon").checked && document.getElementById("method_coupon").checked) ) {
        if (document.getElementById("deal[Online][link]").className == 'fieldGray') {
            error_message  += "This deal type requires the link field completed.\n"
            validate_ok = false;
        }
    }

    validate_ok = validate_ok &  warn_about_types();

    if (init_error_message != error_message) {
        alert(error_message);
    }

    return validate_ok;
}

function warn_about_types() {
    var warned_about_types = document.getElementById("warned_about_types").value;
    if (warned_about_types == 1) {
        return true;
    }
    var inputs = document.getElementsByTagName('input');
    for (var i = 0; i < inputs.length; i ++) {
        var inputname = inputs[i].getAttribute('name');
        if (!inputname || inputname.indexOf('Types') < 0) {
            continue;
        }
        if (inputs[i].checked) {
            return true;
        }
    }
    document.getElementById("warned_about_types").value = 1;
    error_message += "- You did not select any Deal Types. Please choose some Deal Types if there are any that are appropriate for the deal you are posting/revising."
    return false;

}

function ajax_start()
{
    document.getElementById("feedbackBox").style.display = "none";
    document.getElementById('ajax').style.display = 'block';
}

function ajax_end()
{
    document.getElementById('ajax').style.display = 'none';
}


function comments_page(page, deal_id) {

    AjaxEngine.makeReplaceCall(
        'comments_page',
        {
            'parameters' : {
                'cmd'         : 'comments_page',
                'comments_page' : page,
                'DealID'      : deal_id
            },
            'timeout'    : 20000,
            'onLoading'  : function() { ajax_start();  scroll_to_element("commentCount"); },
            'onComplete' : function() { ajax_end(); },
            'onError'    : function() { ajax_end(); alert('An error has occured. Please try again.'); },
            'onTimeout'  : function() { ajax_end(); alert('The request has timed out. Please try again.'); }
        },
        undefined,
        undefined,
        500
    );
}

function post_comment(deal_id)
{
    var form_comment = get_form('post_comment_form');
    if (!form_comment) {
        return;
    }
    if (form_comment.elements['vote']) {
        for (counter = 0; counter < form_comment.elements['vote'].length; counter++) {
            if (form_comment.elements['vote'][counter].checked)
                vote = form_comment.elements['vote'][counter].value;
        }
    } else {
        vote = 0;
    }

    comment_temp  = form_comment.elements['commentinput'].value;

    var params = {
        'cmd' : 'post_comment',
        'DealID'  : deal_id
    }

    if ( comment_temp.split(" ").join("").split("\n").join("").length >= 1 && comment_temp != 'Post your comment here') {
        params['comment'] = comment_temp;
    }
    if (vote != 0) {
        params['vote'] = vote;
    }
    if (form_comment.elements['amountsaved_comment'] && form_comment.elements['amountsaved_comment'].value.length >=1) {
        var amount_val = form_comment.elements['amountsaved_comment'].value;
        params['amount'] = parseFloat(amount_val);
        if (isNaN(params['amount']) || params['amount'] != amount_val) {
            alert("The amount you have entered is invalid. Please enter a valid number.");
            return;
        }
        params['amount'] = params['amount'].toFixed(2);
        if (!is_valid_amount(params['amount'])) {
            alert("The amount you have entered is out of range");
            return;
        }
    }

    if (form_comment.elements['search']) {
        params['search'] = form_comment.elements['search'].value;
    } else {
        params['search'] = "";
    }

    if (params['comment'] || params['vote'] || params['amount']) {
        document.getElementById('inlineComment').style.display = 'none';
        AjaxEngine.makeReplaceCall(
            'comments_page',
            {
                'parameters' : params,
                'timeout'    : 10000,
                'onLoading'  : function() { ajax_start(); },
                'onComplete' : function() { ajax_end(); },
                'onError'    : function() { ajax_end(); alert('An error has occured. Please try again.'); },
                'onTimeout'  : function() { ajax_end(); alert('The request has timed out. Please try again.'); }
            },
            undefined,
            undefined,
            500
        );
    } else {
        alert('Please enter your comment or press Cancel to abort.')
    }
}

/* used from deals lists */
function post_a_comment(deal_id, url, location, popup) {
    id = deal_id;
    if (popup == 1) {
        id = 'popup_' + deal_id 
    }

    var params = {
        'cmd' : 'post_comment',
        'popup' : popup,
        'DealID'  : deal_id
    }

    if (location) params['location'] = location;

    comment_temp  = document.getElementById('commentinput_' + id).value;
    if ( comment_temp.split(" ").join("").split("\n").join("").length >= 1 && comment_temp != 'Post your comment here') {
        params['comment'] = comment_temp;
    }
    
    vote = 0
    for(i=1;i<=3;i++) {
        if (document.getElementById('vote_' + i + '_' + id).checked) {
            vote = document.getElementById('vote_' + i + '_' + id).value;
        } 
    }
    if (vote != 0) {
        params['vote'] = vote;
    }

    if (params['comment'] || params['vote']) {
        AjaxEngine.makeReplaceCall(
            'comments_page',
            {
                'parameters' : params,
                'url'        : url,
                'timeout'    : 10000,
                'onLoading'  : function() { ajax_start(); },
                'onComplete' : function() { ajax_end(); },
                'onError'    : function() { ajax_end(); alert('An error has occured. Please try again.'); },
                'onTimeout'  : function() { ajax_end(); alert('The request has timed out. Please try again.'); }
            },
            undefined,
            undefined,
            500
        );
    } else {
        alert('Please enter your comment or press Cancel to abort.')
    }
}

function remove_moderate_comment(moderate) {
    liid = 'comm_li_' + moderate;
    $('#' + liid).remove();
}

function delete_comment(ref_type, ref_id, comment_no, url, popup, moderate) {
    var answer = confirm("Are you sure you want to delete this comment?");
    if (!answer) {
        return false;
    }

    if (!moderate) {
        moderate = 0;
    }
    
    var params = {
        'cmd' : 'delete_comment',
        'popup' : popup,
        'moderate': moderate,
        'RefType' : ref_type,
        'RefID'  : ref_id,
        'CommentNo': comment_no
    }
    
    AjaxEngine.makeReplaceCall(
        'comments_page',
        {
            'parameters' : params,
            'url'        : url,
            'timeout'    : 10000,
            'onLoading'  : function() { ajax_start(); },
            'onComplete' : function() { ajax_end(); },
            'onError'    : function() { ajax_end(); alert('An error has occured. Please try again.'); },
            'onTimeout'  : function() { ajax_end(); alert('The request has timed out. Please try again.'); }
        },
        undefined,
        undefined,
        500
    );
}

function email_friend()
{
    var from = get_element_value("FromEmail");
    var to = get_element_value("ToEmail");
    var mesg = get_element_value("Message");

    AjaxEngine.makeReplaceCall(
        'email_friend',
        {
            'parameters' : {
                'cmd'  : 'email_friend',
                'from' : from,
                'to'   : to,
                'mesg' : mesg
            },
            'onLoading'  : function() { ajax_start(); },
            'onComplete' : function() { ajax_end(); },
            'onError'    : function() { ajax_end(); alert('An error has occured. Please try again.'); },
            'onTimeout'  : function() { ajax_end(); alert('The request has timed out. Please try again.'); }
        },
        undefined,
        undefined,
        500
    );
}

function report_amount_saved()
{
    if (!document.getElementById("user_amount_saved_on_deal")) {
        return;
    }
    var amt = parseFloat(document.getElementById("user_amount_saved_on_deal").value);
    if (isNaN(amt) || amt != document.getElementById("user_amount_saved_on_deal").value) {
        alert("The amount you have entered is invalid. Please enter a valid number.");
        return;
    }
    amt = amt.toFixed(2);
    if (!is_valid_amount(amt)) {
        alert("The amount you have entered is out of range");
        return;
    }

    rate_deal(4, amt);
}

function rate_deal(rate_type, rate_value)
{
    if (rate_type == 1 && ((rate_value ==  1 && document.getElementById("voteControlPos").className == 'selectedVote') ||
        (rate_value == -1 && document.getElementById("voteControlNeg").className == 'selectedVote'))) {
        return;
    }

    AjaxEngine.makeReplaceCall(
        'comments_page',
        {
            'parameters' : {
                'cmd'         : 'rate_deal',
                'rate_type'   : rate_type,
                'rate_value'  : rate_value,
                'DealID'      : deal_id
            },
            'timeout'    : 20000,
            'onLoading'  : function() { ajax_start(); },
            'onComplete' : function() { ajax_end(); },
            'onError'    : function() { ajax_end(); alert('An error has occured. Please try again.'); },
            'onTimeout'  : function() { ajax_end(); alert('The request has timed out. Please try again.'); }
        },
        undefined,
        undefined,
        500
    );

}

function get_more_comments(delta) {
    current_ts = document.getElementById('ts_start');
    if(!current_ts) return false;

    ts_end = parseInt(current_ts.innerHTML);
    ts_st = ts_end - delta;

    AjaxEngine.makeReplaceCall(
        'more_comments',
        {
            'parameters' : {
                'ajax'        : 1,
                'ts_start'    : ts_st,
                'ts_end'      : ts_end
            },
            'timeout'    : 20000,
            'onLoading'  : function() { ajax_start(); },
            'onComplete' : function() { ajax_end(); },
            'onError'    : function() { ajax_end(); alert('An error has occured. Please try again.'); },
            'onTimeout'  : function() { ajax_end(); alert('The request has timed out. Please try again.'); }
        },
        undefined,
        undefined,
        500
    );

}

function update_more_comments() {
    document.getElementById('dealComments').innerHTML += document.getElementById('moreContent').innerHTML;
}

function switch_vote(vote) {
    if (!document.getElementById("voteControlPos") || !document.getElementById("voteControlNeg")) {
        return;
    }
    if (vote >  0) {
        document.getElementById("voteControlPos").className = 'selectedVote';
        document.getElementById("voteControlNeg").className = '';
    } else {
        document.getElementById("voteControlPos").className = '';
        document.getElementById("voteControlNeg").className = 'selectedVote';
    }
}

function show_post_comment_form()
{
    var elem_inline_comment = document.getElementById('inlineComment');
    if (!elem_inline_comment) {
        return;
    }
    elem_inline_comment.style.display = 'block';
    scroll_to_element("inlineComment");
}

function scroll_to_element(elem_id)
{
    var elem = document.getElementById(elem_id);
    if (!elem) {
        return;
    }
    if (elem.x) {
    	var x = elem.x ? elem.x : elem.offsetLeft;
    	var y = elem.y ? elem.y : elem.offsetTop;
    	window.scrollTo(x, y);
    } else {
        elem.scrollIntoView();
    }
}


function confirm_delete()
{
    var confirm_del = confirm("Please confirm that you would like to\nremove this deal permanently from Dealio.com");

    if (confirm_del) {
        return true;
    }
    return false;
}

function set_deal_product_id(id)
{
    var prod_id = document.getElementById("deal[ProdID]");
    if (!prod_id) {
        return false;
    }
    prod_id.value = id;
}

function check_product_id()
{
    var prod_name = document.getElementById("deal[ProductName]");
    if (!prod_name) {
        return false;
    }

    if (prod_name.value != LAST_PRODUCT_NAME) {
        set_deal_product_id(0);
    }

    return true;
}

function is_valid_amount(amt)
{
    if (!amt || amt > 99999999.99 || amt < 0) {
        return false;
    }

    return true;
}

function check_store_name( event, element )
{
   if((event && event.keyCode != 40) && (event && event.keyCode != 38) && (event && event.keyCode != 13)){
    element.setAttribute( 'autocomplete', 'off' );
    trimmed = element.value.replace( /^\s+/, '' ).replace( /\s+$/, '' ).replace( /^w{3}\./i, '' );
    if ( trimmed == GRAYTEXT_STORE )
        return true;
    //request only when a non alphanumeric caracter is inserted

    sns_box = document.getElementById( 'store_names_suggestions' );
    int=-1;
    //create ajax request
    parameters = {
        cmd: 'stores_list',
        store_search_start: trimmed
    };
    url = document.location.href.split('?')[0];

    AjaxEngine.makeReplaceCall(
        'store_name_finder',
        {
            parameters: parameters,
            url: url,
            timeout: 20000,
            onComplete: function() {  },
            onError : function() { alert('An error has occured. Please try again.'); },
            onTimeout : function() { alert('The request has timed out. Please try again.'); }
        }
    );
    }
}

function close_stores_list()
{
    var suggestion_box = document.getElementById( 'store_names_suggestions' );
    if ( suggestion_box )
        suggestion_box.style.display = 'none';
}
function check_blur(){
	if(tname.className!='store_name')
	{
		close_stores_list();
	}
}
function select_store( StoreName, StoreID )
{
    var store_name = document.getElementById( 'deal[StoreName]' );
    store_name.value = StoreName;
    var store_id = document.getElementById( 'deal[StoreID]' );
    store_id.value = StoreID;
}
var int=-1;
function highlight_store(event,obj){
	if(event && event.keyCode == 40){
	next=int+1;
	if(document.getElementById('store_'+next)){
		int++;
		prev = int-1;
		if(document.getElementById('store_'+prev)){
		document.getElementById('store_'+prev).className='';
		}
		document.getElementById('store_'+int).className='selected';
		store_name = document.getElementById('store_'+int).innerHTML;
		store_name = store_name.replace( '&amp;', '&' );
		select_store(store_name,document.getElementById('store_'+int).name);
	       
	}
	}else if (event && event.keyCode == 38){
	next=int-1;
	if(document.getElementById('store_'+next)){	
		int--;
		document.getElementById('store_'+int).className='selected';
        store_name = document.getElementById('store_'+int).innerHTML;
		store_name = store_name.replace( '&amp;', '&' );
		select_store(store_name,document.getElementById('store_'+int).name);
		
	        prev = int+1;
		if(document.getElementById('store_'+prev)){
		document.getElementById('store_'+prev).className=''
		}
	}
	}else if(event && event.keyCode == 13){
		close_stores_list(event);
	}
	
}
var tname;
function check_clicks(e){
var targ;
if (!e)
  {
    var e=window.event;
      }
      if (e.target)
        {
	      targ=e.target;
	}
	else if (e.srcElement)
	{
	      targ=e.srcElement;
	}
	if (targ.nodeType==3) // defeat Safari bug
	{
	      targ = targ.parentNode;
	}
	
	tname=targ;
	//alert("You clicked on a " + tname + " element.");
}

function bulk_delete_comments(url) {
    ids = new Array();
    $('#dealComments ul li input[type=checkbox]').each(function() {
        if ( $(this).is(':checked') ) {
            ids.push(this.id)
        }
    });

    if ( ids.length == 0 ) {
        alert('No comment selected');
        return;
    }
    
    var answer = confirm("Are you sure you want to delete all " + ids.length + " selected comments?");
    if (!answer) {
        return false;
    }

    var params = {
        'cmd' : 'delete_bulk_comments',
        'moderate' : 1,
        'list': ids.join('-')
    }
    
    AjaxEngine.makeReplaceCall(
        'comments_page',
        {
            'parameters' : params,
            'url'        : url,
            'timeout'    : 10000,
            'onLoading'  : function() { ajax_start(); },
            'onComplete' : function() { ajax_end(); },
            'onError'    : function() { ajax_end(); alert('An error has occured. Please try again.'); },
            'onTimeout'  : function() { ajax_end(); alert('The request has timed out. Please try again.'); }
        },
        undefined,
        undefined,
        500
    );
}

