// Log function to check if Mozilla is the user-agent and make a console.log if true.
function myConsole(text){
    if(jQuery.browser.mozilla == true){
        try {
            console.log(text);
        } catch(e) {
            console = {
                log: function() {}
            }
        }
    } else {
        //alert(text);
    }
}

// AJAX function to handle urls and send it to a element with a id (id)
function ajax(id, url){

    var newurl = url+'&'+'randomnumber='+Math.random();
    $('#'+id+'').load(url ,{}, function(){
        return true;
    })
}

function showArtwork(){
    $('#artworkeditor').show();
    $("#audioRemember").hide();
}

function finishArtwork(){
    $('#artworkRemember').hide();
}

function disablePublish(){
    $('#publishbutton').attr("disabled",true);
    $('#publishmorebutton').attr("disabled",true);
    $('#vpublishbutton').attr("disabled",true);
    $('#vpublishmorebutton').attr("disabled",true);
}

if(typeof($) != 'undefined')
{
    $.fn.ajaxLoadingAnim = function()
    {
        return $(this).each(function(){
            var ajaxLoadingImage = $('<div class="ajaxLoadingAnimContainer"><img src="/images/MiniShop-v2-editor/ajax-loader.gif" width="16" height="16" alt="Please wait" title="Please wait"/></div>');

            $(this)
                .empty()
                .append(ajaxLoadingImage)
                .ajaxStop(function(){
                    $(this)
                        .find('.ajaxLoadingAnimContainer')
                            .remove();
                });
        });
    }
}

// AJAX form sender to a event, and put the results in container.
function invoke(f, event, c, callback) {
    var container   = $('#'+c);
    var form        = $(f);
    
    // add loading animation
    container.ajaxLoadingAnim();

    // prepare data
    var params  = $(form).serialize();
    if (event != null){
        params = params+'&'+event;
    }

    // ajax call
    //alert('Invoke:\n '+event+'\n '+params+'\n '+form.attr('action'));
    $.ajax({
        type    : 'post',
        url     : form.attr('action'),
        data    : params,
        cache   : false,
        error	: function(xhr, textStatus, errorThrown){
            alert("AJAX ERROR: Could not fetch the content\n"
                +textStatus+'\n'
                +errorThrown+'\n'+'\n'
                +xhr.statusText+'\n'
                +xhr.status+'\n'
                +xhr.responseText+'\n'
                +xhr.getAllResponseHeaders()+'\n'
                )
        },
        success : function(output){
            container.html(output);
            if(typeof(callback) != 'undefined')
            {
                callback(container);
            }
        }
    });
}


function advanceAJAXajax(id, url){
    // add loading animation
    $('#'+id).ajaxLoadingAnim();

    $.ajax({
        url     : url,
        cache   : false,
        success : function(output){
            $('#'+id).html(output);
        }
    });
}

// redirects to homepage
function gotoStart(){
    window.location='../dashboard/Dashboard.action';
}

// this code will select and copy clipboard all contents in the textarea.
function copyTextAreaTextToClipboard(textAreaId) {
    codevalue = $('#'+textAreaId).val();
    $.copy(codevalue);
}

// this function gets host from current URL. It should be used instead of window.location.host, because this one works differently among different browsers.
function getMyHost()
{
    myHost = window.location.href;
    // if there is no slash in the URL, we will ad one at the end to prevent JS error
    if(myHost.indexOf('/') == -1)
    {
        myHost += '/';
    }
    // if there is an http prefix in the url, we will remove it - we will then search for first slash in the url and mark it as an host end.
    if(myHost.indexOf('http://') != -1)
    {
        myHost = myHost.substr(7);
    }
    // return host in right format
    myHost = myHost.substr(0, myHost.indexOf('/'));
    return myHost;
}

// parses given url and returns whatever's after last slash
function getFileNameFromURL(myURL)
{
    if(myURL.lastIndexOf('/') != -1)
    {
        myURL = myURL.substr(myURL.lastIndexOf('/')+1);
    }
    return myURL;
}

// add to favourites function
/***********************************************
* Bookmark site script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

/* Modified to support Opera */
function bookmarksite(title,url){
    if (window.sidebar){ // firefox
        window.sidebar.addPanel(title, url, "");
    } else if(window.opera && window.print){ // opera
        var elem = document.createElement('a');
        elem.setAttribute('href',url);
        elem.setAttribute('title',title);
        elem.setAttribute('rel','sidebar');
        elem.click();
    } else if(document.all){ // ie
        window.external.AddFavorite(url, title);
    }
}

// encodes html so it won't be displayed on the output as HTML, but as a code. Prevents adding unwanted 3rd party javascript or other dangerous code
function encodeMyHtml(fsval)
{
    var lsencodedHtml = fsval;
    lsencodedHtml = lsencodedHtml.replace(/&/, "&amp;");
    lsencodedHtml = lsencodedHtml.replace(/</, "&lt;");
    lsencodedHtml = lsencodedHtml.replace(/>/, "&gt;");
    lsencodedHtml = lsencodedHtml.replace(/</, "&lt/");
    lsencodedHtml = lsencodedHtml.replace(/\r\n/, "<br>");
    lsencodedHtml = lsencodedHtml.replace(/\n/, "<br>");
    lsencodedHtml = lsencodedHtml.replace(/\r/, "<br>");
    return lsencodedHtml;
}

function download(actionurl,orderparam,form)
{
    window.open(actionurl + '?bpdownload' + '&' + orderparam);
}

function featureProduct(checked,id){
    var s = '/feature/'+id+'/'+checked;
    ajax('messageArea_'+id,'/feature/'+id+'/'+checked);
}

//set url for a new shop in url editor
function setURL(fsval)
{
    document.getElementById('shop.url').value=fsval;
    document.getElementById('suggestionarea').style.display="none";
}

//set url for a new shop in webmaster flow
function setWMURL(fsval)
{
    document.getElementById('url').value=fsval;
    document.getElementById('suggestionarea').style.display="none";
}

function fillStore(form,event,container,actionurl)
{
    $('#indarrow').show();
    myConsole("Invoke");
    var params = $(form).serialize();
    if (event != null){
        params = params+'&'+'randomnumber='+Math.random()+'&'+event;
    };
    myConsole(params);

    $.ajax({
        type: "POST",
        url: form.action,
        data: params,
        success: function(output){
            $('#'+container+'').html(output);
            advanceAJAXajax('featureshop',actionurl);
            invoke(form, 'directToReady', 'bHolder');
        }
    });
}

function hasFreeFeatureSlots(currentNumber, limit)
{
    var cn = parseInt(currentNumber.text());
    if(cn <= parseInt(limit.text()))
    {
        currentNumber.text(cn+1);
        return true;
    } else {
        return false;
    }
}

function addProductInShop(id,url,actionurl)
{
    if(hasFreeFeatureSlots($('#registerinfo .currentlyFeatured'), $('#registerinfo .featurableSlots')))
    {
        myConsole('advanceAJAX '+id+' '+url);
        var newurl = url+'&'+'randomnumber='+Math.random();

        $.ajax({
            url: url,
            cache: false,
            success: function(output){
                $('#'+id+'').html(output);
                myConsole("advanceAJAX: SUCCESS");
                advanceAJAXajax('bHolder',actionurl);
            }
        });
    } else {
        alert('no free slots!');
    }
}

function removeProductFromShop(id, url,actionurl)
{
    var newurl = url+'&'+'randomnumber='+Math.random();
    $('#'+id+'').load(url ,{}, function(){
        var cn = parseInt($('#registerinfo .currentlyFeatured').text());
        $('#registerinfo .currentlyFeatured').text(cn-1);
        advanceAJAXajax('bHolder',actionurl);
        return true;
    })
}

// hide more than 4 items in the webmaster flow
function WMshow4(area)
{
    $('#'+area+' .showMore').hide();
    var anyhiddenitems = false;
    $('#'+area+' .addThisToTheFeaturedList').each(function(i) {
        if(i > 3)
        {
            $(this).parents('li').hide();
            $(this).parents('li').addClass('WMhiddenItem');
            anyhiddenitems = true;
        }
    });

    if(anyhiddenitems == true)
    {
        $('#'+area+' .showMore').click(function(){
            WMshowHiddenItems(area);
            return false;
        });
        $('#'+area+' .showMore').fadeIn('slow');
    }
}

// shows hidden items which were hidden by function above
function WMshowHiddenItems(area)    {
    $('#'+area+' .WMhiddenItem').each(function(){
        $(this).fadeIn('slow');
    });
    $('#'+area+' .showMore').fadeOut('slow');
}

// show or hide featured items in webmaster flow, in right column
function WMtoggleFeatured(button, featuredFrame)
{
    if(button.find('img').attr('src') == '/images/wmFlow_featuredOn.gif')
    {
        featuredFrame.fadeOut('slow');
        button.find('img').attr('src', '/images/wmFlow_featuredOff.gif');
    } else {
        featuredFrame.fadeIn('slow');
        button.find('img').attr('src', '/images/wmFlow_featuredOn.gif');
    }
}

function addProduct(checked,id,shoplet){
    ajax('messageArea_'+id,'/shoplet/ManageShoplet.action?addProduct&productShop='+id+'&checked='+checked+'&shoplet='+shoplet);
}

function featureArtist(checked,id){
    var s = '/feature/'+id+'/'+checked;
    ajax('messageArea_'+id,'FeatureManager.action?featureArtist&artistShop='+id+'&checked='+checked);
}

function showSalesPrice(url)
{
    url =   url
            +'&item='+$('#item]').attr('value')
            +'&price='+$('#item.price]').attr('value')
            +'&isKoda='+$('#item.isKoda').attr('value')
            +'&randomnumber='+Math.random();

    $.ajax({
        url: url,
        cache: false,
        success: function(output){
            $('#salesPrice').text($('select[name=priceCurrency]').attr('value')+' '+output);
            $('.finalPrice').fadeIn('slow');
        }
    });
}

// This function helps avoid the spam bots - credits goes to Nick, it was his idea
function raInfoMailSPAMavoider (RAname, RAlinkName) {
    var RAdomain        = 'redantenna';
    var RAextension     = '.com';
    var RAmailCommand   = 'mailto:';

    if(RAlinkName == '')
    {
        RAlinkName = RAname+'@'+RAdomain+RAextension;
    }

    return $('<a href="'+RAmailCommand+RAname+'@'+RAdomain+RAextension+'">'+RAlinkName+'</a>');
}

// binds previous function to raInfoMailSPAMavoider class
function bindSpamAvoider()
{
    if($('.raInfoMailSPAMavoider').length > 0)
    {
        $('.raInfoMailSPAMavoider').each(function(){
            var mName = '';
            if($(this).html().length > 0)
            {
                mName = $(this).html();
            }
            $(this).replaceWith(raInfoMailSPAMavoider($(this).attr('title'), mName));
        });
    }
}

// this function pitifully does not work in the label shop (throws object error), therefore it can't be triggered here for every page.
function rounded_buttons(where)
{
    var target = $('body');
    if(typeof(where) == 'undefined')
    {
        $('body').prepend('<div class="buttonPreload"><span></span></div>');
    } else {
        target = where;
    }
    target.find('.button,.submit').each(function(){
        if(!$(this).hasClass('button_right'))
        {
            var extraCssClass = $(this).attr('class').split(' ')[1];
            if(typeof(extraCssClass) != 'undefined' && extraCssClass != null && extraCssClass != '')
            {
                extraCssClass = ' '+extraCssClass;
            } else {
                extraCssClass = '';
            }
            $(this).addClass('button_right');
            var buttonWrapper = $('<span class="button_left'+extraCssClass+'"></span>');
            $(this).wrap(buttonWrapper).mouseover(function(){
                $(this).parent().addClass('button_over');
            }).mouseout(function(){
                $(this).parent().removeClass('button_over');
            });
        }
    });
}

function submitFormByAjax(bindedForm, resultTag)
{
    var targetUrl = $(bindedForm).attr('action');
    var submitType = $(bindedForm).attr('type');

    if(typeof(submitType) == 'undefined' || submitType == '' || submitType == null)
    {
        submitType = 'get';
    }

    $.ajax({
        url:targetUrl,
        type:submitType,
        cache:false,
        data:$(bindedForm).serialize(),
        success:function(response)
        {
            $(resultTag).html(response);
        }
    });
    return false;
}

// this function will add style handling to the form default values - default value hides on focus, and if something is entered, it never returns.
function inputDefaultValuesHints()
{
    // todo: when text field is changed into password, it doesn't return back to text field if nothing is entered.
    $('input[value!=""][type="text"]').each(function(){
        $(this)
            .addClass('inputDefaultText')
            .focus(function(){
                $(this)
                    .data('oldValue', $(this).attr('value'))
                    .removeClass('inputDefaultText')
                    .attr('value', '');
                if($(this).attr('name').indexOf('password') != -1)
                {
                    var passwordField = $('<input type="password" class="'+$(this).attr('class')+'" name="'+$(this).attr('name')+'"/>');
                    $(this).replaceWith(passwordField);
                    passwordField.focus();
                }
            })
            .blur(function(){
                if($(this).attr('value') == '')
                {
                    $(this).addClass('inputDefaultText');
                    if($(this).attr('name').indexOf('password') != -1 && $(this).attr('type') == 'password')
                    {
                        alert('is password, reverting to text');
                        var bindedObject = $(this).clone().attr('type', 'text');
                        $(this).replaceWith(bindedObject);
                        bindedObject.focus();
                    }
                    if($(this).data('oldValue') != '')
                    {
                        $(this).attr('value', $(this).data('oldValue'))
                    }
                }
            });
    });
}

function vokePart(form, event, container) {
          invoke(form,event,container);
          document.getElementById('fckeditorWindow').innerHTML = '';
   }

if(typeof($) != 'undefined')
{
    $(function(){
        if($('.date').length > 0)
        {
            $('.date').datepicker();
        }
    });
}

function loadit(place){
        $("#"+place+" a").each(function()   {
            var popupDetailsContainer = $(this);

            popupDetailsContainer.click(function(){
                //alert();
                $('#'+place).load($(this).attr('href'),{},function(){loadit(place);} );
                //alert('');
                return false;
                //alert('');
                //return false;
       });
   }
   );

   $("#"+place+" input").each(function(){
   if ($(this).attr('type') == 'submit'){
       $(this).click(function(){
            invoke(this.form, this.name, place);
            return false;
       })
   }
   })
    }
