window.onerror = function(){
    return true;
}

$(document).ready(function(){

    $.ajaxSetup({
        beforeSend:show_ajax_loading,
        complete:hide_ajax_loading,
        error:handle_ajax_error
    });

})

var clicksArray = new Array()
var refresh_page_after_popup_close = false;

function only_decimal (e){
    //e.which returns the ASCII value
    if(((e.which>=48 && e.which<=59) || e.which == 8 || e.which == 0 || e.which == 46))
    {
        return true;
    }
    else
    {
        return false;
    }
}

function only_integer (e){
    //e.which returns the ASCII value
    if((e.which>=48 && e.which<=59) || e.which == 8 || e.which == 0 )
    {
        return true;
    }
    else
    {
        return false;
    }
}


function dhtmlhistory_add(history,url)
{
    dhtmlHistory.add(history,url)
}
function populatedFieldClick(fieldName){
    if (!clicksArray[fieldName]) {
        clicksArray[fieldName] = true;
        document.getElementById(fieldName).value = '';
    }
}

function update_backbutton_count(){
    $("a[rel='history']").each(function(){
        tital_count = tital_count + 1;
        $(this).attr("backbutton","#"+tital_count);
    })
}


// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function reset_modal(id){
// popup_body_element = $("#" + id)
// popup_body_element.attr("style", "");
// popup_body_height = popup_body_element.attr("scrollHeight") * 1;
//popup_body_height = 70;
//popup_body_element.attr("style","overflow:auto;height:"+popup_body_height+"px");
}

function options_for_date(){
    button_image_url = '/images/calendar.gif'
    return {
        dateFormat: 'dd.mm.yy',
        buttonImage: button_image_url,
        mandatory: true,
        showOn: 'both',
        buttonImageOnly: true
    //        numberOfMonths: 2
    }
}

var max_date;
function set_minimum_end_date(start_date_string, end_date_id){
    start_date = parse_my_date(start_date_string);
    end_date_element = $("#" + end_date_id)
    end_date_string = end_date_element.val();
    end_date = parse_my_date(end_date_string);
    options = options_for_date();
    options.minDate = start_date;
    options.maxDate = max_date;
    options.numberOfMonths = 2;
    end_date_element.datepicker("destroy");
    end_date_element.datepicker(options);
    if (end_date && start_date > end_date) {
        alert("End date has been changed as it cannot be less than start date")
        end_date_element.val(start_date_string);
        
    }
    
}

function parse_my_date(date_string){
    if (date_string != null)
        return Date.parseExact(date_string, "dd.MM.yyyy");
    else {
        return false
    }
}


//function hide_popup(){
//    //     $.ajax({
//    //        type: "POST",
//    //        url: '/users/new',
//    //        data: {
//    //            authenticity_token: 'b1548e48c72194f8ec12fb399b35f8cd38c576c8'
//    //        },
//    //        async: false,
//    //        success: function(request){
//    //            $.modal(request, {closeClass: ('simplemodal-close')})
//    //        }
//    //    })
//    //    alert($('#modalContainer'))
//    //    $.modal($('#modalContainer'),{closeClass: ('simplemodal-close')});
//
//    //    $('#modalContainer').hide()
//}

function show_popup(id){    
    $('#' + id).jqm({ //      onShow: function(h) {
        //        /* callback executed when a trigger click. Show notice */
        //        h.w.fadeIn("fast");
        //        },
        onHide: function(h){
            //        /* callback executed on window hide. Hide notice, overlay. */
            h.w.fadeOut("2000", function(){
                if (h.o)
                    h.o.remove();
            });
            if (refresh_page_after_popup_close == true) {
                location.reload(true);
                refresh_page_after_popup_close = false;
            }
            hide_loader();

        }
    }).jqmShow();
}

function show_shows_iframe()
{
    $("#shows_iframe_loading").hide();
    $("#shows_iframe").show();

}

//function hide_ajax_loading(){
//    //alert("hide ajax loading;")
//    //	$("#wait_for_load").remove();
//    //	$(".jqmOverlay").remove();
//    $(".menu_ajax_loader,.popup_ajax_loader").hide();
//    resize_modal('popup_body')
//}


function resize_modal(id){
    popup_body_element = $("#" + id)
    //popup_body_height = popup_body_element.attr("scrollHeight");
    popup_body_height = $("#popup_div").height() * 1.0 * 0.95
    popup_body_width = popup_body_element.attr("scrollWidth");
    max_height = $(window).height() * 1.0 * 0.95
    max_width = $(window).width();
    left_width = max_width - popup_body_width
    top_width = max_height - popup_body_height
    if (((popup_body_height) < max_height) && (popup_body_width) < max_width){
        $("#popup_body").css('width',popup_body_width)
        $(".jqmWindow").css('width',popup_body_width)
        $(".jqmWindow").css('top',top_width/2+"px")
        $(".jqmWindow").css('left',left_width/2+"px")
    }
    else {
        css = {
            overflow: 'auto',
            width: popup_body_width + "px",
            height: (max_height - 100) + "px"
        }
        popup_body_element.css(css);
        $(".jqmWindow").css('width',popup_body_width);
        popup_body_element.css('overflow-x','hidden')
    }
}

//function show_ajax_loading(){
//    //$("body").append('<div style="height: 100%; width: 100%; position: fixed; left: 0pt; top:0pt; z-index: 2999; opacity: 0.5;" class="jqmOverlay"/>');
//    //$('body').append("<div id='wait_for_load' style='z-index: 3000;background-color: white; border:1px solid black; padding:5px; position: absolute; top: 50%; left: 50%;'><img src=/images/ajax_loader.gif class=loading></div>");
//    $("#menu_ajax_loader").show();
//
//}
//
//function hide_ajax_loading(){
//    //	$("#wait_for_load").remove();
//    //	$(".jqmOverlay").remove();
//    $("#menu_ajax_loader").hide();
//
//}

function hide_popup(){
    $("#popup_div").jqmHide();
}

function increment_count(id){
    element = $("#" + id)
    element.html(element.html() * 1 + 1);
}

function decrement_count(id, count){
    if (count >= 0) {
        element = $("#" + id)
        element.html(element.html() * 1 - count);
    }
    else {
        element = $("#" + id)
        element.html(element.html() * 1 - 1);
    }
}

function flash_settings(new_settings){
    
    var default_settings = {
        flash_url: "/flash/swfupload.swf",
        file_size_limit: "3072",
        file_types: "*.jpg;*.gif;*.png",
        file_types_description: "Jpg or Gif or Png Image Files",
        file_queue_limit: 10,
        button_image_url: "/images/interface/btns/browse-files.gif", // Relative to the Flash file
        button_width: "132",
        button_height: "36",
        button_placeholder_id: "spanButtonPlaceHolder",
        button_text: '',
        button_cursor: SWFUpload.CURSOR.HAND,
        button_text_style: ".theFont { font-size: 16; }",
        button_text_left_padding: 12,
        button_text_top_padding: 3,
        debug: false // Set to true to find out why things aren't working
    }
    return jQuery.extend(default_settings, new_settings)
}

var ajax_request_count = 0;
function show_ajax_loading(){
    $("#flash_message").hide()
    
    // show ajax loader
    ajax_request_count = ajax_request_count + 1;
    show_loader();
    //$("input[type=submit]").attr("disabled", true)
    //$("input[type=button]").attr("disabled", true)
    //  $("input[type=submit]").attr("temp_tag",$("input[type=submit]").val())
    $(".please_wait").each(function(a){
        $(this).attr("after_click", $(this).val());
        $(this).val('Please Wait');
    })
//    set_onclick_for_back_button()
}

function show_loader()
{
    $("#page_ajax_loader").show();
}

function hide_ajax_loading(){
    //    $('div').each(function(index) {
    //        $(this).attr('tabIndex', index+1);
    $("#errorExplanation").attr('tabIndex', 1);
    $("#flash_message").attr('tabIndex', 2);
    $("#errorExplanation").focus();
    $("#flash_message").focus();
    //        $("#client_errros_div").focus();
    //    });
    $(".please_wait").each(function(a){
        $(this).val($(this).attr("after_click"))
    });

    //hide ajax loader
    ajax_request_count = ajax_request_count - 1;
    if(ajax_request_count <= 0)
    {
        hide_loader();
    }

    $("input[type=submit]").attr("disabled", false);
    $("input[type=button]").attr("disabled", false);
    $("#site_search").val('')
    set_onclick_for_back_button()
    $(".only_decimal").keypress(only_decimal);
}

function hide_loader()
{
    $("#page_ajax_loader").hide();
    
}


function handle_ajax_error()
{
// not needed as no the complete event is always fired.
// console.log("from handle error ajax loading")
// ajax_request_count = ajax_request_count - 1;
// console.log(ajax_request_count);
}

function show_client_side_errors(error_message){
    //$(".status_message").hide();
    //$("#errorExplanation").html("");
    $("#client_errors_div").show();
    $("#client_errors_div").addClass("errorExplanation");
    $("#client_errors_div").html("<h2>Oops! There are some errors: </h2><ul></ul>");
    $("#client_errors_div ul").html("<li>" + error_message + "</li>");
    //$("#errorExplanation").hide();
    $("#client_errors_div").focus();
}

function show_client_side_validations(message){
    $("#client_errros_div").html("");
    $(".status_message").hide();
    $("#errorExplanation").html("");
    $("#client_errros_div").show();
    $("#client_errros_div").addClass("errorExplanation");
    $("#client_errros_div").html("<h2>Oops! There are some issues with the form</h2><p>There were problems with the following fields:</p><ul></ul>");
    //	$("#client_errros_div").append("<div class='errorExplanation'>");
    ($("#errorExplanation ul li")).each(function(){
        $("#client_errros_div ul").html("<li>" + $(this).text() + "</li>");
    })
    //$("#client_errros_div ul").html("<li> You can select maximum " + no_of_files + " files or One of the selected files exceeds the size limit or <br/> You might have logged of the account.  </li>");
    $("#client_errros_div ul").html("<li>" + message + "</li>");
    $("#errorExplanation").hide();
    $("#client_errros_div").focus();
    
    
//	$("#errorExplanation").hide();
//	$("#client_errros_div").addClass("errorExplanation");
    
}


function show_please_select_at_least_one_user_message(size,select_type)
{
    $("#errorExplanation").html("");
    $("#client_errros_div").show();
    $("#client_errros_div").addClass("errorExplanation");
    $("#client_errros_div").html("<h2>Oops! There are some issues with the form</h2><p>There were problems with the following fields:</p><ul></ul>");
    //	$("#client_errros_div").append("<div class='errorExplanation'>");
    ($("#errorExplanation ul li")).each(function(){
        $("#client_errros_div ul").html("<li>" + $(this).text() + "</li>");
    })
    if(size == 0)
    {
        $("#client_errros_div ul").html("<li> Please select atleast one , to send a message or to delete it. </li>");
    }
    else
    {
        $("#client_errros_div ul").html("<li> There should be atleast one contact </li>");
    }
    $("#errorExplanation").hide();
    $("#client_errros_div").focus();
            
}
        
function generate_popup_url(url,data)
{
    $('#popup_body').html('<img src=/images/interface/icons/ajax-loader.gif / class=loading>');
    show_popup('popup_div');
    response = $.ajax({
        type : "GET",
        url: url,
        data: data,
        async : false
    })
    $('#popup_body').html(response.responseText);
    $('#popup_div #popup_header').html('New Custom Template');
    resize_modal('popup_body');
}
        
        

function show_selected_count()
{
    var j = 0;
    $(".check_box:checked").each(function(){
        j += 1;
    })
    if(j == 0)
    {
        return "No Contacts Selected"
    }
    else if(j == 1)
    {
        return "1 Contact Selected"
    }
    else
    {
        return j + " Contacts Selected"
    }
                        
}
                    
function add_cookie_array(name,value) {
    var array_string = $.cookie(name)
    array_string += "," + value
    $.cookie(name, array_string);
}
            
function remove_cookie_array(name,value){
             
    var array_string = $.cookie(name)
    array = array_string.split(',');
    array = array.filter(function(x){
        return x != value
    })// remove value from array
    array_string = array.join(",");
    $.cookie(name, array_string);
}
        
function cookie_array(name){
            
    var array_string = $.cookie(name)
    if(array_string && array_string != "")
    {
        return array_string.split(",");
    }
    else
    {
        return false;
    }
}
           
function messages_and_user_cookies_in_messages(message_ids,user_ids){
    var cookie_user_ids = $.cookie("cookie_user_ids")
    var cookie_message_ids = $.cookie("cookie_message_ids")
    //cookie_user_ids += user_ids.join(',')
    //cookie_message_ids += message_ids.join(',')
    if($.cookie("cookie_user_ids"))
    {
        $.cookie("cookie_user_ids", cookie_user_ids + "," + user_ids.join(','));
    }
    else
    {
        $.cookie("cookie_user_ids", user_ids.join(','));
    }
    if($.cookie("cookie_message_ids"))
    {
        $.cookie("cookie_message_ids", cookie_message_ids + "," + message_ids.join(','));
    }
    else
    {
        $.cookie("cookie_message_ids", message_ids.join(','));
    }
//return $.cookie("cookie_user_ids");
}
                    
function remove_messages_and_user_cookies_in_messages(message_id,user_id)
{
    var cookie_user_ids = $.cookie("cookie_user_ids")
    var cookie_message_ids = $.cookie("cookie_message_ids")
    cookie_user_ids = cookie_user_ids.split(",")
    cookie_message_ids = cookie_message_ids.split(",")
    cookie_user_ids = cookie_user_ids.pop(user_id)
    cookie_message_ids = cookie_message_ids.pop(message_id)
    $.cookie("cookie_message_ids", cookie_message_ids);
    $.cookie("cookie_user_ids", cookie_user_ids);
                       
}
                        
function add_message_and_user_cookies_in_messages(message_id,user_id)
{
    var cookie_user_ids = $.cookie("cookie_user_ids")
    var cookie_message_ids = $.cookie("cookie_message_ids")
    cookie_user_ids += user_id
    cookie_message_ids += message_id
    $.cookie("cookie_message_ids", cookie_message_ids);
    $.cookie("cookie_user_ids", cookie_user_ids);
                        
}
                        
                        
                        
function clear_cookie_data()
{
    $.cookie("cookie_user_ids","");
    $.cookie("cookie_message_ids","");
    $.cookie("cookie_unread_message_user_ids","");
    $.cookie("cookie_unread_message_ids","");
    $.cookie("cookie_sent_message_ids","");
    $.cookie("cookie_contact_ids","");
}
                        
//function show_client_side_error_for_max_file_size(exceeded_file_name)
//{
// $("#client_errros_div").addClass("errorExplanation");
//    $("#client_errros_div").html("<h2>Oops! There are some issues with the form</h2><p>There were problems with the following fields:</p><ul></ul>");
//    //	$("#client_errros_div").append("<div class='errorExplanation'>");
//    ($("#errorExplanation ul li")).each(function(){
//        $("#client_errros_div ul").html("<li>" + $(this).text() + "</li>");
//    })
//    $("#client_errros_div ul").html("<li> The File named " + exceeded_file_name + " exceeds size limit  </li>");
//    $("#errorExplanation").hide();
//}
//
                    
function addb_customize_css_changes(){
    $("#profile-box").css('margin-bottom',0)
    $(".column-small").css('width','206px')
    $(".column-wide").css({
        'width':'734px',
        'padding':'0px'
    })
    $("#column-right").css('margin','0px')
    $("#contacts_list_div").css({
        'width':'704px',
        'padding-left':'20px'
    })
    $("#mail_inbox").css({
        'width':'667px',
        'padding-left':'20px'
    })
    $("#mail_sent").css({
        'width':'667px',
        'padding-left':'20px'
    })
}

function load_index_page(){
        
        
    var index_url = "/dashboard/user_design_templates";
    window.location = index_url;
        
//response = $.ajax({type : "GET",
//url : index_url,
//data : {},
// async : false})
        
// $('#column-right').html(response.responseText);
}

//to fix the bug of incorrect browser height in chrome and safari.
//code from the link http://cksource.com/forums/viewtopic.php?f=6&t=13222&start=10
//this function is automatically called by the fck library
function FCKeditor_OnComplete( editorInstance ) {
    var fck_iframe = document.getElementById(editorInstance.Name+'___Frame');
    var fck_editing_area = fck_iframe.contentDocument.getElementById('xEditingArea');
    fck_editing_area.style.height = '100.1%';
    setTimeout(function() {
        fck_editing_area.style.height = '100%'
    }, 100);
}

// upload error ( Global upload error)

function show_upload_error(file, code, message){
    $("#client_errros_div").html("");
    $(".status_message").hide();
    $("#errorExplanation").html("");
    $("#client_errros_div").show();
    $("#client_errros_div").addClass("errorExplanation");
    $("#client_errros_div").html("<h2>Oops! There are some issues with the form</h2><ul></ul>");
    //	$("#client_errros_div").append("<div class='errorExplanation'>");
    ($("#errorExplanation ul li")).each(function(){
        $("#client_errros_div ul").html("<li> Some error occured while uploading the item, please try again </li>");
    })
    //$("#client_errros_div ul").html("<li> You can select maximum " + no_of_files + " files or One of the selected files exceeds the size limit or <br/> You might have logged of the account.  </li>");
    $("#client_errros_div ul").html("<li> Some error occured while uploading the item, please try again </li>");
    $("#errorExplanation").hide();
    $("#client_errros_div").focus();
}

function show_map(show_id,permalink,url)
{

    my_width = 745;
    my_height = 540;
    my_left =(screen.width/2) - (my_width/2);
    my_top = (screen.height/2) - (my_height/2);
    window.open(url+'/shows/'+ show_id +'/shows_direction_container?permalink='+permalink,'View show on map','left=' + my_left + ',top=' + my_top + ',height=' + my_height + ',width=' + my_width + ',screenX=' + my_left + ',screenY=' + my_top +',scrollbars=1,resizable=1,location=0')
    return false
}

function parameters_from_url(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}