
function GeneralFormPopUp(params){
    var buttons ={};
    var form;

    if(params =='' || params === undefined){
        params={};
    }

    if(params['query_params'] =='' || params['query_params'] === undefined){
        params['query_params']={};
    }   

    /*check input parameters*/
    if(params['action'] =='' || params['action'] === undefined){
        params['action']='/';
    }

    params['reload_url']=params['reload_url']||''; 

    if(parseInt(params['width']) < 1){
        params['width']=500;
    }

    $('body').append('<div class="GeneralFormPopUp"></div>');

    params['REQUEST_FROM_FACEBOX']=1;
    $('.GeneralFormPopUp').load(params['action'],params['query_params'],function(){

        var dlg=$(this);

        form=dlg.find('form');

        var showResponse = function(responseText, statusText, xhr)  { 
            var result;
            var errorfound=0;

            /*try to find the input fields that have errors and mark them in the dialog*/
            $(responseText).find('.errfield').each(function(){
                $(this).find('input').each(function(){
                    var input=form.find("[name='"+$(this).attr('name')+"']");
                    var div_container=input.closest('div');
                    div_container.addClass('errfield');
                    div_container.append('<span class="errmsg">Fältet måste fyllas i</span>');
                });
            });

            /*try to find an error message on the result page and print it in the dialog*/
            $(responseText).find('.error').each(function(){
                form.append('<div class="error">'+$(this).html()+'</div>');
                errorfound=1;
            });

            if(errorfound == 0){
                /*close dialog and load the page that is in the forms action*/
                dlg.dialog('destroy').remove();
                
                if(params['formCallback']){
                    params['formCallback'](form);
                }

                if(params['callback']){
                    params['callback'](responseText);
                }
                
                if(params['reload_url']){
                    location.href=params['reload_url'];
                }
            }
        }
        
        /*add ajax function to the form*/
        var options = {
            success: showResponse
        }

        form.submit(function(e){
            if(e.target.onsubmit){
                if(e.target.onsubmit()){
                    $(this).ajaxSubmit(options);
                }
                return false;
            }
            $(this).ajaxSubmit(options);
            return false;
        });

        /*find all buttons in the form and add them as buttons in the dialog*/
        $($(this).find('.button').get().reverse()).each(function(){
            
            var action=$(this).attr('name');
            $(this).hide();
            
            if(action !='CANCEL'){
                buttons[$(this).val()]=function() {
                    form.append('<input type="hidden" name="'+action+'" value="1"/>');
                    form.submit();
                };
            }
        });

        /*add a default cancel button*/
        buttons['Avbryt']=function() {
            $(this).dialog('destroy').remove();
        };

        var dialog_params={
            resizable: false,
            modal: true,
            width: parseInt(params['width']),
            buttons: buttons,
            close: function(){
                $(this).dialog('destroy').remove();
            },
            open:function () {
                var uiDialog=$(this).closest(".ui-dialog");
                var button=uiDialog
                    .find("[type=button]");
                button.addClass("button");
                button.unbind('mouseenter mouseleave');
                button.unbind('focus');
                button.removeClass('ui-state-default');
            }
        };

        if(params.dialogClass){
            dialog_params.dialogClass=params.dialogClass;
        }

        $('.GeneralFormPopUp').dialog(dialog_params);
    });        
}

function form_validate_general(obj,callback,params){
    var result=true;

    if(params===undefined){
        params={};
    }

    var form;
    if(obj.is( "form" )){
        form = obj;
    }else{
        form = obj.closest('form');
    }

    form.find('input').each(function(){
        
        if($(this).attr('data-required')){
        
            $(this).click();
            if($(this).val() == $(this).attr('data-default') || $(this).val()==''){
                $(this).closest('div').addClass('errfield');
                $(this).val($(this).attr('data-default'));
                result=false;
            }else{
                $(this).closest('div').removeClass('errfield');
            }
        }
    });

    form.find('textarea').each(function(){
        
        if($(this).attr('data-required')){

            $(this).click();
            
            if($(this).val() == $(this).attr('data-default') || $(this).val()==''){
                $(this).closest('div').addClass('errfield');
                $(this).val($(this).attr('data-default'));
                result=false;
            }else{
                $(this).closest('div').removeClass('errfield');
            }
        }
    });

    if(result){
        if(callback!==undefined){
            callback(params['image'],params['form']);
        }

        var error=form.find('.error');
        if(error.length>0){
            error.remove();
        }

    }else{

        var error=form.find('.error');
        if(error.length<1){
            form.append('<div class="error"></div>');
            error=form.find('.error');
        }                
        
        error.html('Obligatoriskt fält saknar värde');

        if(params['image']!==undefined){
            $('#'+params['image']).hide();
        }
    }

    return result;
}

function GetCurrencyStandardDefs() {
  
  var defsMatch = "1 000,00 kr".match(/^(.*)1([^0]*)000(([^0])(0+))?([^0].*)?/);
  var defs;
  if(defsMatch) {
    defs = {};
    defs.prefix = defsMatch[1]?defsMatch[1]:"";
    defs.thousand_sep = defsMatch[2]?defsMatch[2]:"";
    defs.decimal_sep = defsMatch[4]?defsMatch[4]:"";
    defs.decimals = defsMatch[5]?defsMatch[5].length:0;
    defs.suffix = defsMatch[6]?defsMatch[6]:"";
  }
  return defs;
}

function FormatPriceString(value, defs) {
  if(!defs) {
    defs = GetCurrencyStandardDefs();
  }
  var isNegative = false;
  var s = "";
  var intValue = Math.abs(parseInt(value));
  if(value < 0) {
    isNegative = true;
  }
  while(intValue > 0) {
    var temp = "" + (intValue % 1000);
    while(temp.length < 3) {
      temp = "0" + temp;
    }
    if(defs.thousand_sep && s.length) {
      s = defs.thousand_sep + s;
    }
    s = temp + s;
    intValue = parseInt(intValue / 1000);
  }
  s = s.replace(/^[\s0]+/g, '');
  if(isNegative) {
    s = "-" + s;
  }
  if(defs.prefix) {
    s = defs.prefix + s;
  }
  if(defs.decimals) {
    s += defs.decimal_sep;
    var decimals = "" + Math.round((Math.abs(value) - Math.abs(parseInt(value))) * Math.pow(10,defs.decimals), 0);
    while(decimals.length < defs.decimals) {
      decimals = "0" + decimals;
    }
    s += decimals;
  }
  if(defs.suffix) {
    s += defs.suffix;
  }
  return s;
}
function recaptchav3_append_token(form, token) {
    var token_input = "token";
    if( ! form.find('[name='+token_input+']').length ) {
        form.append('<input type="hidden" name="'+token_input+'" value="'+token+'"/>');
    } else {
        form.find('[name='+token_input+']').val(token);
    }
}
function delete_wishlist_item_confirm() {
    return confirm('Är du säker på att du vill ta bort artikeln från önskelistan?');
}
function delete_wishlist_confirm(wishlist_id) {
    if (confirm('Är du säker på att du vill ta bort önskelistan?')) {
        delete_wishlist(wishlist_id);
    } else {
        return 0;
    }
}
