/* 
agileForms.js: used to validate administrative forms for Agility CMS

notes:
    some basic assumptions are made (because it's the CMS and we control it)
    'save' is always the ID of the form being validated
    every element in the form will have one of the following CSS class names
    requiredInput: for text input, select and text area elements indicates required
    
    optional: indicates the value is optional so wont fail valadation
    optionalHtml: implies we're using FCK editor dialogue
    requiredHtml:
    optionalFile: a file element, optional 
    requiredFile: a file element, required
    optionalReplaceFile: a file element, is optional but must check if replacing a file before committing
    
    validationMessages are stored in message containers that have an id in the form msgElementName
    


*/
var additionalValidationExitCode=false;
//parseStringAsQuery: utility to parse the query params that we use in filters
function parseStringAsQuery(stringToParse){
    // The return is a collection of key/value pairs
    var returnDictionary = {};
    // Gets the query string, starts with '?'
    //alert(stringToParse);
    var querystring = decodeURI(stringToParse);
    if (!querystring) {
        return {};
    }
    
    // '&' seperates key/value pairs
    var pairs = querystring.split("&");
    //alert(pairs.length)
    // Load the key/values of the return collection
    for (var i = 0; i < pairs.length; i++) {
        var keyValuePair = pairs[i].split("=");
       // alert(keyValuePair[0])
        //alert(keyValuePair[1])
        returnDictionary[keyValuePair[0]]= keyValuePair[1];
    }
    // Return the key/value dictionary

    return returnDictionary;
}




//agValidateInput: validates a simple text input
function agValidateInput(paramInput){

    // check if the class is required or optional
    if (paramInput.hasClass('requiredInput')){
        if (jQuery.trim(paramInput.val())==''){
            return false;
        }
    }
    // check if the class is required or optional
    if (paramInput.hasClass('requiredPrice')){
        if (jQuery.trim(paramInput.val())==''){
            showError('This value is required!',paramInput);
            return false;
        }
        if (isNaN(paramInput.val())){
            showError('Only numeric values are allowed here!',paramInput);
            return false;
        }
        if (parseFloat(paramInput.val())==0){
            showError('You must enter a value greater than zero!',paramInput);
            return false;
        
        }
    }
     // check if the class is required or optional
    if (paramInput.hasClass('optionalPrice')){
        if (jQuery.trim(paramInput.val())==''){
            paramInput.val('0');
        }
        if (isNaN(paramInput.val())){
            showError('Only numeric values are allowed here!',paramInput);
            return false;
        }
        
    }
   
    return true;
}

//agValidatePicture: validates a file upload dialogue that is intended for use as a picture
function agValidatePicture(paramInput){
    
    //ALWAYS: there will be two additional form elements that tag along with this element
        // has_picture: 1 if there is already an image associated with 'this record'
        // change_picture: we set this to '1' if user is uploading a replacement image
        
    // capture tag along element values
    var hasImage=parseInt($('#has_picture').val());
    var changeImage=false;   
    var loadImage=false;
    //first capture the value 
    var nImage=jQuery.trim(paramInput.val());
    //alert(nImage);
    if (nImage.length!=0){
        changeImage=true;
        
    }
    if (changeImage==true){
        //check that file conforms
       var m=nImage.toString().toLowerCase();
        var c=m.lastIndexOf(".")
        m=m.substr((c+1),4)
        if ((m !='jpg')&&(m !='png')&&(m !='gif')){
           showError("Please select a JPG, GIF or PNG format for the picture !",paramInput); 
           return false;
        }
    }    
    
    //now check if there is already an image
    if ((hasImage==1)&&(changeImage==true)){
        // need to 
        if (!confirm("Please confirm that you wish to replace the picture that is currently being used!")){
            changeImage=false;
        }
    }
    
    
    // check if the class is required or optional
    if (paramInput.hasClass('requiredFile')){
        if ((hasImage==0) && (changeImage==false)){
           showError("Please select a JPG or PNG format for the picture !",paramInput); 
           return false;
        }
    }
    
    if (changeImage==true){
        $('#change_picture').val('1');
    }
    
    return true;
}

//agValidateResource: validates a file upload dialogue 
function agValidateResource(paramInput){
    
    //ALWAYS: there will be two additional form elements that tag along with this element
        // has_picture: 1 if there is already an image associated with 'this record'
        // change_picture: we set this to '1' if user is uploading a replacement image
        
    // capture tag along element values
    var hasImage=parseInt($('#has_picture').val());
    var changeImage=false;   
    var loadImage=false;
    //first capture the value 
    var nResource=jQuery.trim(paramInput.val());
    
    if (nResource.length!=0){
        changeImage=true;
        
    }
    if (changeImage==true){
        //check that file conforms
       var m=nResource.toString().toLowerCase();
        var c=m.lastIndexOf(".")
        m=m.substr((c+1),4)
        //need to ensure that the resource extension conforms to allowed list
        switch (m){
            case 'jpg': //ok
                break;
            case 'gif': //ok
                break;
            case 'png': //ok
                break;
            case 'doc': //ok
                break;
            case 'docx': //ok
                break;
            case 'pdf'://ok
                break;
            case 'ppt': //ok
                break;
            case 'pptx': //ok
                break;
            case 'txt'://ok
                break;
            case 'swf'://ok
                break;
            case 'xls'://ok
                break;
            case 'xlsx'://ok
                break;
            case 'wmv'://ok
                break;
            case 'zip': //ok
            default://not ok
               showError("The filetype you are attempting to upload is not permitted !",paramInput); 
               return false;
               break;
            
        }
    }    
    
    //now check if there is already an image
    if ((hasImage==1)&&(changeImage==true)){
        // need to 
        if (!confirm("Please confirm that you wish to replace the asset / file that is currently asscoiated with this record!")){
            changeImage=false;
        }
    }
    
    
    // check if the class is required or optional
    if (paramInput.hasClass('requiredResource')){
        if ((hasImage==0) && (changeImage==false)){
           showError("Please select a file to be associated with this record !",paramInput); 
           return false;
        }
    }
    
    if (changeImage==true){
        $('#change_picture').val('1');
    }
    
    return true;
}


//showError: display CSS styled error message
function showError(paramMessage, paramElement){
    alert(paramMessage);
    if (paramElement.length!=0){
        paramElement.focus();
    }
    return false;
}



//genericWithHTML: checks form elements based on class
function genericWithHTML(){
    //$('#save').each()
    var message='';
    var elementClassName='';
    var bReturn=true
    $('#save :input').each(function( e, item ){
        //alert($(this).attr('class'));
        message='You must enter a value for ' + $(this).attr('title') + '!';
        if (jQuery.trim($(this).attr('title'))=='') {
            message="You must enter information here!"
        }
        
        var elementClassName=$(this).attr('class');
        
        switch (elementClassName){//test values based on what the class is
            case 'requiredInput': //this value is required
                
                if (jQuery.trim($(this).val())==''){
                    showError(message, $(this));
                    
                    bReturn=false;
                    return false;
                }
                
                break;
            case 'folderInput': //value must be sanitised and is ALWAYS required
                $(this).val(urlSafe($(this).val()));
            
                if (jQuery.trim($(this).val())==''){
                    showError(message, $(this));
                    
                    bReturn=false;
                    return false;
                }
                
                break;
            
            
            case 'requiredPrice': //required numeric
                    if (jQuery.trim($(this).val())==''){
                        showError('This value is required!',$(this));
                        bReturn=false;
                        return false;
                    }
                    if (isNaN($(this).val())){
                        showError('Only numeric values are allowed here!',$(this));
                        bReturn=false;
                        return false;
                    }
                    if (parseFloat($(this).val())==0){
                        showError('You must enter a value greater than zero!',$(this));
                        bReturn=false;
                        return false;
                    
                    }
            case 'requiredPrefix': //telephone prefix in the form +xxxx
                    if (jQuery.trim($(this).val())==''){
                        showError('This value is required!',$(this));
                        bReturn=false;
                        return false;
                    }
                    
                    
            
            case 'optionalPrice': //optional numeric
                    if (jQuery.trim($(this).val())!=''){
                        if (isNaN($(this).val())){
                            showError('Only numeric values are allowed here!',$(this));
                            bReturn=false;
                            return false;
                        }
                    }
                    break;            
            case 'requiredName':// full name is required
                if (jQuery.trim($(this).val())==''){
                    showError(message, $(this));
                    
                    bReturn=false;
                    return false;
                }
                
                break;
            case 'requiredEmail': //required email address
                //test that there's a value
                $(this).val(jQuery.trim($(this).val()));
                if ($(this).val()==''){
                    showError(message, $(this));
                    bReturn=false;
                    return false;
                }
                //test that value conforms to email pattern
                var e=$(this).val();
                if (!checkEmail(e)){
                    message="Please check the email address you have entered as it does not seem to be valid!"
                    showError(message, $(this));
                    bReturn=false;
                    return false;
                }

                break;
            case 'optionalEmail': //optional but must conform to email address pattern
                //test that there's a value
                $(this).val(jQuery.trim($(this).val()));
                if ($(this).val()!=''){
                    //test that value conforms to email pattern
                    var e=$(this).val();
                    if (!checkEmail(e)){
                        message="Please check the email address you have entered as it does not seem to be valid!"
                        showError(message, $(this));
                        bReturn=false;
                        return false;
                    }
                }

                break;
            case 'requiredTelephone'://MUST exist and be numeric only
                $(this).val(fixTelephone(jQuery.trim($(this).val())));
                if ($(this).val()==''){
                    showError(message, $(this));
                    bReturn=false;
                    return false;
                }
                break;                
            case 'optionalTelephone'://if exists then must be numeric only
                $(this).val(fixTelephone(jQuery.trim($(this).val())));
                break;                
                       
            case 'requiredSelect'://drop down list is required
                //alert(message)
                //alert(jQuery.trim($(this).val()));
                message='You must select a value for ' + $(this).attr('title') + '!';
                //alert($(this).val());
                if ((jQuery.trim($(this).val())=='0')||(jQuery.trim($(this).val()).length==0)){
                    showError(message, $(this));
                    bReturn=false;
                    return false;
                }
                break;
            
            case 'requiredFile'://file (picture) is required
                if (!agValidatePicture($(this))){
                    bReturn=false;
                    return false;
                }
                
                break;
            
            case 'requiredResource'://file (any allowed asset) is required
                if (!agValidateResource($(this))){
                    bReturn=false;
                    return false;
                }
                
                break;
            case 'optionalFile': //optional file upload dialogue
               if (jQuery.trim($(this).val()).length!=0){
                    if (!agValidatePicture($(this))){
                        bReturn=false;
                        return false;
                     }
                               
               }
                break;
            case 'optionalHTML': //html editor dialogue (not required but must capture value)

                //if ($('#txtHTML').length){
                //        var data = $('#txtHTML').val();
                //        var carrier=$('#FCKDATASOURCE').val();
                //        $('#' + carrier).val(data);
                //    }
                break;
            case 'tagAlong': //pick up on any tag alongs (listboxes)
                var nameOfSource='#' + $(this).attr('id') + 'Source'
                var source= '#' + $(nameOfSource).val() // name of element to which this is bound
                //alert($(source).val());
                var message="Please ensure you select an option from the " + $(source).attr('title')
                if ((jQuery.trim($(source).val())=='0')||(jQuery.trim($(source).val()).length==0)){
                    showError(message, $(source));
                    bReturn=false;
                    return false;
                }
                $(this).val($(source).val())
                break;  
            case 'filterInput'://pickup filter name value and insert into inputname
                var nameOfSource= $(this).val();
                var nameOfDestination='#input'+ $(this).attr('id').replace('Data','');
                var objData=parseStringAsQuery($('#'+ nameOfSource).val());
                $(nameOfDestination).val(objData[nameOfSource].toString());
            case 'requiredDate'://date input is required
                var message="Please ensure you select a valid date !" 
                if (jQuery.trim($(this).val()).length==0){
                    showError(message, $(this));
                    bReturn=false;
                    return false;
                }
                break;
                
            
            case '': //unhandled class
                break;
        }
    });
    
    if ($('#additionalValidation').length){
        if (bReturn){
            if (additionalValidationExitCode==false){
                    var addHandler=$('#additionalValidation').val();
                    eval(addHandler);
                    if (additionalValidationExitCode==false){
                        bReturn=false;
                        return false;
                    }
            }
        }
    }
    //pickup checkbox values
    var chk=$('#save  input:checkbox');
    if (chk.length!=0){
        for (var c=0;c<chk.length;c++){
            //clear the payload container for this group of checkboxes
            var n=$(chk[c]).attr('name').replace('option','#input');
            $(n).val('0');
        } 
        for (var c=0;c<chk.length;c++){
            //clear the payload container for this group of checkboxes
            var n=$(chk[c]).attr('name').replace('option','#input');
            if ($(chk[c]).attr('checked')){
                    $(n).val($(n).val() + ',' + $(chk[c]).attr('value'));
            }
        } 
    }    
    
     if ($('#debugSave').length){
    
        if ($('#debugSave').attr('checked')!=true){
            // alert($('#debugSave').attr('checked'))
            $('#save').attr('target','keyhole');
            //alert($('#save').attr('target'));
        }
        else
        {
        $('#save').attr('target','_blank');
        }
     }
     else{
        $('#save').attr('target','keyhole');
     }
    
    // alert("here");
    return bReturn;
}





// validateAsset: tests that form for uploading a media object [asset] has been populated correctly before posting 
function validateAsset(){
    var message='';
    var elementClassName='';
    var bReturn=true
    $('#save :input').each(function( e, item ){
        //alert($(this).attr('class'));
        
        
        var elementClassName=$(this).attr('class');
        
        switch (elementClassName){//test values based on what the class is
            case 'requiredInput': //this value is required
                
                if (jQuery.trim($(this).val())==''){
                    showError(message, $(this));
                    
                    bReturn=false;
                    return false;
                }
                
                break;
            case 'fileInput': //this value is required
                message='Please select a file before proceeding!';
                if (jQuery.trim($(this).val())==''){
                    showError(message, $(this));
                    
                    bReturn=false;
                    return false;
                }
                
                break;
        }
     });
     
    $('#save').attr('target','keyhole');
    return bReturn;
}

//validateAssetCaption: capture and redirect the post
function validateAssetCaption(){
    $('#saveCaption').attr('target','keyhole');
    return true;

}

//populateLinkTypeSelectorOptions: triggered hwen use selects the type of link they would like to create (banner advertisements)
function populateLinkTypeSelectorOptions(paramValue){
      if ($('#debugPanel').length){
         var html=$('#debugPanel').html() + '<br/><strong>populateLinkTypeSelectorOptions</strong><br/>';
         html+='param_url: <a href="' + paramValue + '">click for url</a><br/>';
         html+='paramValue: ' + paramValue + '<br/>';
         $('#debugPanel').html(html);
      
      }
    $('#inputLinkTypeSelectorOptions').html('<span style="margin: 0 24px;">please wait ... loading</span><span><img src="../images/spinner.gif" alt="please wait a moment" style="border:0px;"/></span>');
    $('#inputLinkTypeSelectorOptions').load(paramValue);
    return void[0];

}

//fixTelephone: removes non-numeric characters from user entry
function fixTelephone(param_value){
    var ret_value='';
    var wip_value=param_value;
    var a_values='1234567890+'
    //alert(wip_value.length);
    for (var i=0;i<=wip_value.length;i++){
    //alert(wip_value.charAt(i))
        for (var x=0;x<=a_values.length;x++){
            if (wip_value.charAt(i)==a_values.charAt(x)){
                ret_value+=wip_value.charAt(i)
            }
        }
    } 
    //alert(ret_value);
    return ret_value;   
}

//checkEmail: pattern test for email
function checkEmail(svalue){
    var str=svalue;
    var sinvalid="!,£,\$,%,',\&";
    
    
	var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)|(')|(%)|(")/; // not valid
	var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; // valid
    if (!reg1.test(str) && reg2.test(str)) { // if syntax is valid
    	return true;
   	}
    return false;
}


//checkDiscountCode: specific routine for validating discount codes
function checkDiscountCode(){
    var exitCode=false;
    
    //alert("checkDiscountCode");
    //first, test that we have a valid selection in inputdiscountCodeType
    var discountCodeType=parseInt($('#inputdiscountCodeType').val());
    //alert(discountCodeType);
    switch(discountCodeType){
        case 1: //discountTypeFlat
            // must have a value > 0 in the inputredemptionValue
            var d=$('#inputredemptionValue').val();
            //check if numeric
            if (parseFloat(d)==0){
                showError('You must enter a discount value greater than zero!',$('#inputredemptionValue'));

            }
            else{
             exitCode=true;
            }
            break;
        case 2: //discountTypePercentage
            // must have a value > 0 < 50in the inputredemptionValue
            var d=$('#inputredemptionValue').val();
            if (parseFloat(d)==0){
                showError('You must enter a discount percentage greater than zero (e.g. for 10% enter 0.1 as the value of the discount!',$('#inputredemptionValue'));
                break;
            }
            if (parseFloat(d)> 0.5){
                if (confirm("Are you sure you want to offer such a high discount, the value you have entered is greater than 50% ?")){
                    exitCode=true;
                }
            }
            else{
                 exitCode=true;
            }
            break;
        case 3: //discountTypeShipping
            // value in the inputredemptionValue is ignored
            $('#inputredemptionValue').val('0');
             exitCode=true;
            break;
        
    }
    
    //check start and end dates
    var s=new Date($('#inputredemptionStartDate').val());
    var e=new Date($('#inputredemptionEndDate').val());
    if (s > e){
        showError('The start date must be less than the end date!',$('#inputredemptionStartDate'));
        exitCode=false;
    }
    
    additionalValidationExitCode=exitCode;
    return void[0];

}

//urlSafe: returns a sanitised string suitable for use as a URL
function urlSafe(paramValue){
    var allowedCharacters="abcdefghijklmnopqrstuvwxyz1234567890"
    var returnValue='';
    var checkValue=paramValue.toLowerCase();
    for (var i=0;i<checkValue.length;i++){
        if (allowedCharacters.indexOf(checkValue.substr(i,1))!=-1){
            returnValue+=checkValue.substr(i,1);
        }
    }
    //ensure we aren't using one of the reserved folder names
    if (returnValue=="asp"){returnValue=''}
    if (returnValue=="images"){returnValue=''}
    if (returnValue=="common"){returnValue=''}
    if (returnValue=="resources"){returnValue=''}
    if (returnValue=="style_sheets"){returnValue=''}
    if (returnValue=="wip"){returnValue=''}
    if (returnValue=="model"){returnValue=''}
    if (returnValue=="remote"){returnValue=''}
    
    
    return returnValue;
}

//validateURL: stub that triggers validateVirtualFolder from onchange event - but only if len > 0
function validateURL(){
    $('#inputurl').val(urlSafe($('#inputurl').val()));
    if ($('#inputurl').val()==''){
         showError("You must enter a folder name!", $('#inputurl'));
         return void[0];
    }
    eval('validateVirtualFolder(1);');
    return void[0];
}
//validateVirtualFolder: performs a JSON get to test if the value of a folder is valid / usable
function validateVirtualFolder(paramCheck){

additionalValidationExitCode=false;
    //paramID,paramFolder,progress_bar_url
    var d=new Date();
    var url=$('#base').val() + "v2010/ajax.asp?objectid=1205&tag=_checkMerchantFolder&uid=" + $('#uid').val() + "&folder=" + $('#inputurl').val();
    //window.location.href=url;
    //return false;
    $.getJSON(url, function(data){
                        //alert(data.errors);
                        if(data.errors==0){
                             additionalValidationExitCode=true; 
                               if (paramCheck!=1){
                                     $('#save').attr('target','keyhole');
                                     $('#save').submit(); 
                             } 
                        }
                        else{
                            alert(data.message);
                             $('#inputurl').focus();
                            additionalValidationExitCode=false;
                        }
                       
                        
                });                    
                
                
                
  
}


//validateMerchantFormElement: test that we don't have invalid mandatory/enabled tags
function validateMerchantFormElement(){
 additionalValidationExitCode=true;
 var required=parseInt($('#modelrequired').val());
         if (required==1){
                //must display and be required
                if (parseInt($('#inputisenabled').val())==0){
                    showError("This field is required and must be enabled!",$('#inputisenabled'));
                     additionalValidationExitCode=false;
                    return false;
                }
                if (parseInt($('#inputismandatory').val())==0){
                    showError("This field is required and cannot be made optional!",$('#inputismandatory'));
                     additionalValidationExitCode=false;
                    return false;
                }
        }
        return true;
}


//checkComplementaryRelationship: ensure that both fields are different (cannot match)
function checkComplementaryRelationship(){
 additionalValidationExitCode=true;
 
  if (parseInt($('#inputmasterid').val())==parseInt($('#inputchildid').val())){
                     showError("You must ensure that the primary group is different to the complementary group!",$('#inputmasterid'));
                     additionalValidationExitCode=false;
                     return false;
 
    }
}

