function actionResultMessage(classname, text)
{
    $('#ajaxActivity img').hide();
    $('#aa_description').html(text);
    $('#ajaxActivity').addClass(classname).fadeIn(300).delay(6000).fadeOut(300, function(){$('#aa_description').html('&nbsp;'); $('#ajaxActivity').removeClass(classname);$('#ajaxActivity img').show();});
}

function activityMessage(classname, text, time)
{
    $('html').append('<div id="activityMessage" class="activity-message"><span id="aa_description"></span></div>');
    $('#activityMessage #aa_description').html(text);
    $('#activityMessage').addClass(classname).fadeIn(300).delay(time).fadeOut(300, function(){$('#activityMessage').remove();});
}

function showHideActivityWheel(text)
{
    $('#aa_description').html(text);
    $('#ajaxActivity').fadeIn(300).delay(2000).fadeOut(300, function(){$('#aa_description').html('&nbsp;');});
}

function showActivityWheel(text)
{
    $('#activityMessage').remove();
    
    $('#aa_description').html(text);
    $('#ajaxActivity').fadeIn(300);
}

function hideActivityWheel()
{
    $('#ajaxActivity').fadeOut(300, function(){$('#aa_description').html('&nbsp;');});
}

function showAlert(text)
{
    $(body).append('<div class="global-warning"').html(text).css('display', 'none').fadeIn(300).delay(5000).fadeOut(300, function(){$(this).remove()});
}

function field_auto_save(base_url, id, element)
{
    var table = $(element).attr('name');
    var value = $(element).val();
    
    field_save(base_url, table, value, id);
}

function field_save(base_url, table, value, id)
{
    value = $.base64Encode('' + value);
    showActivityWheel('Saving...');
    $.ajax({
        type: "POST",
        url: base_url + "ajax/save-field",
        data: "table="+table+"&id="+id+"&value="+value,
        success: function(data){
            if(data!='')
            {
                $('#ajaxActivity').hide();
                activityMessage('warning', 'There was an error saving.', 3000);
            }
            else
                hideActivityWheel();
        }
    });
}

function disableInput(element, enable_condition)
{
    if(element.val() == enable_condition)
        $('#' + element.attr('id') + '_pixel').removeAttr('disabled').focus().select();
    else
        $('#' + element.attr('id') + '_pixel').attr('disabled', 'disabled');
}

function rgb2hex(rgb)
{
    if(rgb[0] == '#')
        return rgb.substring(1);
        
    var parts = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    // parts now should be ["rgb(0, 70, 255", "0", "70", "255"]
    
    if(parts!=null)
    {
        delete (parts[0]);
        for (var i = 1; i <= 3; ++i) {
            parts[i] = parseInt(parts[i]).toString(16);
            if (parts[i].length == 1) parts[i] = '0' + parts[i];
        }
        return parts.join('');
    }
    
    return '000000';
}

function urldecode(str)
{
    return decodeURIComponent((str + '').replace(/\+/g, ' '));
}

function divToggle(id)
{
    $('#'+id).slideToggle(function(){
        if($('#' + id + '-button').length > 0)
        {
            if($(this).css('display') == 'block')
                $('#' + id + '-button').addClass('close');
            else
                $('#' + id + '-button').removeClass();
        }
    });
}

function switchPanel(panel1, panel2)
{
    if($('#'+panel1).is(':visible'))
    {
        $('#'+panel1).hide(0, function(){
            $('#'+panel1+'-button').removeClass('choice-button-active');
            $('#'+panel2+'-button').addClass('choice-button-active');
            $('#'+panel2).show();
        });
    }
    else
    {
        $('#'+panel2).hide(0, function(){
            $('#'+panel2+'-button').removeClass('choice-button-active');
            $('#'+panel1+'-button').addClass('choice-button-active');
            $('#'+panel1).show();
        });
    }
}

function viewFileBrowser(base_url, result_field, field, id, filter, size)
{
    if(!size)
        size = '0x0';
    window.open(base_url + 'file-browser/index/'+result_field+'/'+field+'/'+id+'/'+filter+'/'+size, '_blank', "resizable=0,scrollbars=1,width=980,height=700,top=0,left=0");
}

function createRaphaelIcon(type, disabled, id, color)
{
    $('#'+id).html('');
    
    var colors_active = {green: ['#007c00', '#7be65a'],
                         red: ['#cc0000', '#ffe7e7'],
                         blue: ['#1E5B7C', '#7ABDDE']};
    var colors_disabled = {green: ['#9bc89b', '#e5f7e5'],
                            blue: ['#B0CBD9', '#7ABDDE']};
    if(disabled)
        var colors = colors_disabled[color];
    else
        var colors = colors_active[color];
    if(type == 'leftarrow')
    {
        var canvas = Raphael(document.getElementById(id), 9, 12);
        canvas.path('M6,2L2,6L6,10').attr({stroke:colors[0], 'stroke-width': 3, 'stroke-linecap': 'round'});
        // highlight
        //canvas.path('M8,3L5,6').attr({stroke:colors[1], 'stroke-width': 1, 'stroke-linecap': 'round'});
    }
    if(type == 'rightarrow')
    {
        var canvas = Raphael(document.getElementById(id), 9, 12);
        canvas.path('M2,2L6,6L2,10').attr({stroke:colors[0], 'stroke-width': 3, 'stroke-linecap': 'round'});
        // highlight
        canvas.path('M8,7L4,11').attr({stroke:colors[1], 'stroke-width': 0.5, 'stroke-linecap': 'round'});
    }
    if(type == 'cross')
    {
        //cross
        var paper = Raphael(document.getElementById(id), 12, 12);
        paper.path('M2,2L10,10').attr({stroke:colors[0], 'stroke-width': 3, 'stroke-linecap': 'round'});
        paper.path('M10,2L2,10').attr({stroke:colors[0], 'stroke-width': 3, 'stroke-linecap': 'round'});
        // highlight
        paper.path('M12,3L9,6').attr({stroke:colors[1], 'stroke-width': 1, 'stroke-linecap': 'round'});
        paper.path('M6,9L3,12').attr({stroke:colors[1], 'stroke-width': 1, 'stroke-linecap': 'round'});
    }
}

function createColorPicker(target, tables, table_ids, values, base_url)
{
    var html = '<div class="color">';
    html += '<div class="color-box" id="'+tables[0]+'-box" name="'+tables[0]+'"></div>';
    html += '<input maxlength="6" tableid="'+table_ids[0]+'" class="autosave input-text cpicker" type="text" name="'+tables[0]+'" id="'+tables[0]+'" value="'+values[0]+'" />';
    //html += '<div class="slider-value" id="slider-'+tables[1]+'" name="'+tables[1]+'" maxvalue="100" tableid="'+table_ids[1]+'"></div>';
    html += '<input class="autosave numeric input-text percentage-value" type="text" tableid="'+table_ids[1]+'" id="'+tables[1]+'" name="'+tables[1]+'" value="'+values[1]+'" maxlength="3" />';
    html += '<a class="button" href="javascript:clearColourValue(\''+tables[0]+'\', \''+tables[1]+'\')" title="Remove background colour">None</a>';
    html += '</div>';
    $('#'+target).html(html);
    //Set background color
    $('#'+tables[0]+'-box').css('backgroundColor', '#' + values[0]);
    //Color picker
    $('#'+tables[0]+'-box').click(function(){
        $(".color-picker-wrapper").css('top', $(this).position().top);
        $(".color-picker-wrapper").css('left', $(this).position().left);
        $(".color-picker-wrapper").fadeIn(500);
        current_color = rgb2hex($('#'+tables[0]+'-box').css('backgroundColor'));
        $(".color-picker-wrapper").ColorPickerSetColor(current_color);
        //Save after choosing color
        $('.colorpicker').unbind('mouseleave');
        $('.colorpicker').mouseleave(function(){
            $(".color-picker-wrapper").fadeOut(500);
            if(current_color != '')
            {
                field_save(base_url, tables[0], current_color, table_ids[0]);
                $('#' + tables[0]).val(current_color);
                $('#' + tables[0] + '-box').css('backgroundColor', '#' + current_color);
                current_color = '';
            }
        });
    });
    //Update color on blur
    $('#'+tables[0]).blur(function(){
        $('#'+tables[0]+'-box').css('backgroundColor', '#' + $(this).val());
    });
}

function createFontPicker(target, tables, table_ids, values)
{
    var html = '<div class="sub-panel font">';
    html += '<label for="'+tables[0]+'">Font</label>';
    html += '<select tableid="'+table_ids[0]+'" name="'+tables[0]+'" id="'+tables[0]+'" data-placeholder="Font family" class="chzn-select test-width autosave">';
    html += '<option value=""></option>';
    html += '<option ' + (values[0]=='arial'?'selected="selected" ':'') + 'value="arial">Arial</option>';
    html += '<option ' + (values[0]=='helvetica'?'selected="selected" ':'') + 'value="helvetica">Helvetica</option>';
    html += '<option ' + (values[0]=='georgia'?'selected="selected" ':'') + 'value="georgia">Georgia</option>';
    html += '<option ' + (values[0]=='times'?'selected="selected" ':'') + 'value="times">Times</option>';
    html += '</select>';
    html += '</div>';
    html += '<div class="side-300">';
    html += '<div class="sub-panel boundaries">';
    html += '<label for="'+tables[1]+'">Font size</label><div class="slider-value" id="slider-'+tables[1]+'" name="'+tables[1]+'" tableid="'+table_ids[1]+'" maxvalue="72"></div>';
    html += '<input class="autosave numeric input-text pixel-value" type="text" id="'+tables[1]+'" name="'+tables[1]+'" tableid="'+table_ids[1]+'" value="'+values[1]+'" maxlength="3" />';
    html += '</div>';
    html += '<div class="sub-panel boundaries">';
    html += '<label for="'+tables[2]+'">Line height</label><div class="slider-value" id="slider-'+tables[2]+'" name="'+tables[2]+'" tableid="'+table_ids[2]+'" maxvalue="72"></div>';
    html += '<input class="autosave numeric input-text pixel-value" type="text" id="'+tables[2]+'" name="'+tables[2]+'" tableid="'+table_ids[2]+'" value="'+values[2]+'" maxlength="3" />';
    html += '</div>';
    html += '</div>';
    $('#'+target).html(html);
}

function create_message(recipient_type, recipient_options, base_url)
{
    $.ajax({
        type: "POST",
        url: base_url + "ajax/send-message-form",
        data: "type="+recipient_type+"&options="+recipient_options,
        success: function(data){
            $('html').append(data);
            showModalWindow('new-message-popup', true);
        }
    });
}

function create_recipient_list(selected_list, list_type, list_ids, base_url, redirect)
{
    $.ajax({
        type: "POST",
        url: base_url + "ajax/recipient_lists_form/" + redirect.replace('/', '--'),
        data: "selected_list="+selected_list+"&list_type="+list_type+"&list_ids="+list_ids,
        success: function(data){
            $('html').append(data);
            showModalWindow('new-recipient-popup', true);
        }
    });
}

function is_favourite(list_type, list_ids, base_url)
{
    $.ajax({
        type: "POST",
        url: base_url + "ajax/add_remove_favourite",
        data: "list_type="+list_type+"&list_ids="+list_ids,
        success: function(data){
            window.location.reload(true);
        }
    });
}

function deleteSelectedFile(base_url, element, table, table_id)
{
    if(confirm("Do you wish to remove the selected file?"))
    {
        field_save(base_url, table, '', table_id);
        $('#'+element+' .delete-text').hide();
        $('#'+element+' .thumb').html('');
    }
}

function deleteSelectedFileAsync(base_url, element)
{
    if(confirm("Do you wish to remove the selected file?"))
    {
        $('#'+element+' .delete-text').hide();
        $('#'+element+' .thumb').html('');
        $('#'+element+'-field').val('');
    }
}

function removeVideoAsync(name)
{
    if(confirm("Do you wish to remove the selected video?"))
    {
        $('#'+name).val('');
        $('#'+name+'-name').val('');
    }
}

function generate_testimonial_url(base_url, client_id, company_id)
{
    showActivityWheel('Generating URL...');
    $.ajax({
        type: "POST",
        url: base_url + "ajax/client_testimonial_url/" + client_id + "/" + company_id,
        success: function(data){
            $('#client-url-' + client_id).html('<a class="testimonial" target="_blank" href="' + data + '">' + data + '</a>');
            hideActivityWheel()
        ;}
    });
}

function limitChars(textid, limit, infodiv)
{
    limitChars_aux(textid, limit, infodiv);
    
    $('#' + textid).keyup(function(){
        limitChars_aux(textid, limit, infodiv);
    });
}

function limitChars_aux(textid, limit, infodiv)
{
    if($('#'+textid).lenght == 0)
        return false;
    
    var text = $('#'+textid).val();
    var textlength = text.length;
    if(textlength > limit)
    {
        $('#' + infodiv).html('You have 0 characters left.');
        $('#' + textid).val(text.substr(0,limit));
        return false;
    }
    else
    {
        $('#' + infodiv).html('You have '+ (limit - textlength) +' characters left.');
        return true;
    }
}

function showModalWindow(id, deleteAfter)
{
    
    //$('html #mask').remove();
    $('html').append('<div id="mask"></div>');
    
    var speed = 400;
    id = '#' + id;
    //Get the screen height and width
    var maskHeight = $(document).height();
    var maskWidth = $(window).width();
 
    //Set height and width to mask to fill up the whole screen
    $('#mask').css({'width':maskWidth,'height':maskHeight,'opacity':0,'display':'block'});
     
    //transition effect     
    $('#mask').fadeTo(speed, 0.2);
 
    //Get the window height and width
    var winH = $(window).height();
    var winW = $(window).width();
           
    //Set the popup window to center
    $(id).css('top',  $(window).scrollTop() + winH/2-$(id).height()/2);
    $(id).css('left', winW/2-$(id).width()/2);
 
    //transition effect
    $(id).fadeIn(speed);
    $('iframe').hide();
     
    //if close button is clicked
    $(id + ' .close').click(function (e) {
        //Cancel the link behavior
        e.preventDefault();
        $('#mask').fadeOut(speed);
        $(id).fadeOut(speed, function(){$('iframe').show();if(deleteAfter){$(this).remove()}});
    });     
     
    //if mask is clicked
    $('#mask').click(function () {
        $(this).fadeOut(speed);
        $(id).fadeOut(speed, function(){$('iframe').show();if(deleteAfter){$(this).remove()}});
    });
}

function view_news_detail(base_url, id)
{
    $.ajax({
        type: "POST",
        url: base_url + "ajax/view-news-detail",
        data: "id="+id,
        success: function(data){
            $('html').append(data);
            showModalWindow('news-detail-popup', true);
        }
    });
}

function register_msg()
{
    alert('Please register or login to access this feature.');
}

function initSocialShare(base_url)
{
    $('.social-share').each(function(){
        var type = $(this).attr('social').split('-');
        var title = '<ul><li><a href="javascript:shareOnFB(\'' + base_url + '\', \'' + type[0] + '\', \'' + type[1] + '\');" title="">Share on Facebook</a></li><li><a href="javascript:shareOnTwitter(\'' + base_url + '\', \'' + type[0] + '\', \'' + type[1] + '\')" title="Share on Twitter">Share on Twitter</a></li><li><a href="javascript:sendToFriend(\'' + base_url + '\', \'' + type[0] + '\', \'' + type[1] + '\');" title="Send to a friend">Send to a friend</a></li></ul>';
        $(this).attr('social', title);
        $(this).tipsy({html:true, title:'social', trigger:'click', customclass: 'social', fade:true, offset: 5});
    })
}

function shareOnFB(base_url, type, id)
{
    $.ajax({
        type: "POST",
        url: base_url + "ajax/share_on_fb",
        data: "type="+type+"&id="+id,
        success: function(data)
        {
            if(data!='')
                window.open(data, "cb-share", "status=1,toolbar=0,location=0,resizeable=0,width=640,height=480");
        }
    });
}

function shareOnTwitter(base_url, type, id)
{
    $.ajax({
        type: "POST",
        url: base_url + "ajax/share_on_twitter",
        data: "type="+type+"&id="+id,
        success: function(data)
        {
            if(data!='')
                window.open(data, "cb-share", "status=1,toolbar=0,location=0,resizeable=0,width=640,height=480");
        }
    });
}

function sendToFriend(base_url, type, id)
{
    $.ajax({
        type: "POST",
        url: base_url + "ajax/send_to_friend_form",
        data: "type="+type+"&id="+id,
        success: function(data){
            if(data!='')
            {
                $('html').append(data);
                showModalWindow('send-to-friend-popup', true);
            }
        }
    });
}

function previewNewWork(base_url, id)
{
    showActivityWheel('Loading...');
    $.ajax({
        type: "POST",
        url: base_url + "agency/new-work-detail/" + id + "/preview",
        success: function(data){
            if(data!='')
            {
                $('html').append('<div id="new-work-window" class="new-work-detail">' + data + '</div>');
                showWorkModalWindow('new-work-window');
            }
            hideActivityWheel();
        ;}
    });
}

function showNewWorkPopup(base_url, id)
{
    showActivityWheel('Loading...');
    $.ajax({
        type: "POST",
        url: base_url + "agency/new-work-detail/" + id,
        success: function(data){
            if(data!='')
            {
                $('body').append('<div id="new-work-window" class="new-work-detail">' + data + '</div>');
                showWorkModalWindow('new-work-window');
            }
            hideActivityWheel();
        ;}
    });
}

function showNewWorkPopupFromEmail(base_url, id, email)
{
    showActivityWheel('Loading...');
    $.ajax({
        type: "POST",
        url: base_url + "agency/new-work-detail/" + id + "?email=" + email,
        success: function(data){
            if(data!='')
            {
                $('body').append('<div id="new-work-window" class="new-work-detail">' + data + '</div>');
                showWorkModalWindow('new-work-window');
            }
            hideActivityWheel();
        ;}
    });
}

function showWorkModalWindow(id, deleteAfter)
{
    
    //$('html #mask').remove();
    $('html').append('<div id="mask"></div>');
    
    var speed = 400;
    id = '#' + id;
    //Get the screen height and width
    var maskHeight = $(document).height();
    var maskWidth = $(window).width();
 
    //Set height and width to mask to fill up the whole screen
    $('#mask').css({'width':maskWidth,'height':maskHeight,'opacity':0,'display':'block'});
     
    //transition effect     
    $('#mask').fadeTo(speed, 0.2);
 
    //Get the window height and width
    var winH = $(window).height();
    var winW = $(window).width();
           
    //Set the popup window to center
    $(id).css('top',  $(window).scrollTop() + 20);
    $(id).css('left', winW/2-$(id).width()/2);
 
    //transition effect
    $(id).fadeIn(speed);
    $('iframe').hide();
     
    //if close button is clicked
    $(id + ' .close').click(function (e) {
        //Cancel the link behavior
        e.preventDefault();
        $('#mask').fadeOut(speed);
        $(id).fadeOut(speed, function(){$('iframe').show();$(this).remove()});
    });     
     
    //if mask is clicked
    $('#mask').click(function () {
        $(this).fadeOut(speed);
        $(id).fadeOut(speed, function(){$('iframe').show();$(this).remove()});
    });
}

function old_browser_message(base_url)
{
    $.ajax({
        type: "POST",
        url: base_url + "ajax/old-browser",
        success: function(data){
            if(data!='')
            {
                $('body').append('<div id="old-browser-window">' + data + '</div>');
                showModalWindow('old-browser-window', true);
            }
        ;}
    });
}

function clearColourValue(color, alpha)
{
    $('#' + color + '-box').css('backgroundColor', '#ffffff');
    $('#' + color).val('');
    $('#' + color).trigger('blur');
    $('#' + alpha).val('100');
    $('#' + alpha).trigger('blur');
}

function updateAgenciesLocation(base_url)
{
    $('#agency_regions_div').html('Loading...');
    $.ajax({
        type: "POST",
        url: base_url + "ajax/update-agency-location",
        data: "disciplines=" + $('#agency_disciplines').val(),
        success: function(data){
            $('#agency_regions_div').html(data);
            $('.chzn-select').chosen();
        ;}
    });
}

function updateCaseStudyLocation(base_url)
{
    $('#case_study_regions_div').html('Loading...');
    $.ajax({
        type: "POST",
        url: base_url + "ajax/update-case-study-location",
        data: "sectors=" + $('#case_study_sectors').val(),
        success: function(data){
            $('#case_study_regions_div').html(data);
            $('.chzn-select').chosen();
        ;}
    });
}
