
// Globals
var ServicesPath = '/_ajax/';
var ErrorHandlersMap = {};
var AliasErrorsMap = {};
var ErrorsElement = null;
var DefaultAjaxOptions = {
    type: 'POST',
    dataType: 'XML',
    timeout: 10000,
    success: function(response, status) {
        response = text2xml(response);
        if(HasErrors(response)) {
            HandleErrors(response);
        }
    },
    error: function() {
        SystemError('Service call timed out');
    }
};
var SystemError = function(error) {
    alert(error);
}
var HasErrors = function(response) {
    test = $('error', response);
    return test != null && test.length > 0;
}
var HandleGeneralError = function(response) {
                ErrorsElement.show();
                ErrorsElement.append('<li>' + $('message', response).text() + '</li>');
}
var HandleErrors = function(validator, response) {
                //validator.resetForm();
                
                var fields = {};
                
                $('error', response).each(function() {
                                message = $('message', $(this)).text();
                                field = $('field', $(this)).text();
                                                                
                                // Error handlers
                                if(ErrorHandlersMap[field] != null) {
                                                ErrorHandlersMap[field]($(this));
                                }
                                else {
                                                if(ErrorHandlersMap[message] != null) {
                                                                ErrorHandlersMap[message]($(this));
                                                }
                                                else {
                                                                // Check for aliases
                                                                if(AliasErrorsMap[field] != null) {
                                                                                var aliasFields = {};
                                                                                
                                                                                for(var aliasField in AliasErrorsMap[field]) {
                                                                                                // Call error handlers
                                                                                                if(ErrorHandlersMap[field] != null) {
                                                                                                                ErrorHandlersMap[AliasErrorsMap[field][aliasField]]($(this));
                                                                                                }
                                                                                                else {
                                                                                                                aliasFields[aliasField] = message;
                                                                                                }
                                                                                }
                                                                                
                                                                                AddErrors(validator, aliasFields);
                                                                }
                                                                else {
                                                                                // Check if the field exists
                                                                                if($(field).length == 0) {
                                                                                                HandleGeneralError($(this));
                                                                                }
                                                                                else{
                                                                                                fields[field] = message;
                                                                                }
                                                                }
                                                }
                                }
                                
                                AddErrors(validator, fields);
                });
}
var AddError = function(validator, field, error) {
    var errors = {};
    errors[field] = error;
    validator.showErrors(errors);
}
var AddErrors = function(validator, errors) {
    if(validator != null && validator.showErrors != null) {
        validator.showErrors(errors);
    }
}
// Convert text to XML DOM
var text2xml = function(s) {
 var x, ie = /msie/i.test(navigator.userAgent);
 try{
  var p = ie? new ActiveXObject("Microsoft.XMLDOM") : new DOMParser();
  p.async = false;
 }catch(e){ throw new Error("XML Parser could not be instantiated") };
 try{
  if(ie) x = p.loadXML(s)? p : false;
  else x = p.parseFromString(s, "text/xml");
 }catch(e){ throw new Error("Error parsing XML string") };
 return x;
}; 
    
$(document).ready(function() {
    // Default errors element
    ErrorsElement = $('#errors');
    var options = jQuery.extend(true, {}, DefaultAjaxOptions);
    options.url = ServicesPath + 'Logout.ajax';
    options.type = 'GET';
    
    options.success = function(response, status) {
        location.reload(true);
    }
    
    $('#logout').click(function()
    {
        jQuery.ajax(options);
        return false;
    });
});

$(document).ready(function() {
    
    ErrorHandlersMap["Favorite already exists"] = function() {
        alert("You have already added this page to your favorites");
    }
    
    var options = {};
    options.url = ServicesPath + 'AddUserFavorites.ajax';
    options.type = 'POST';
    options.success = function(response) {
        response = text2xml(response);
        if(HasErrors(response)) {
            HandleErrors({}, response);
        }
        else {
            alert('Added to favorites');
        }
    };
    
    // favorites
    $('.add-favorite').click(function() {
        var imageUrl = $('.sectionIcon').attr('src');
        var title = document.title;
        var description = document.getElementById('pageDescription');
        
        if(description == null)
        {
            description = document.title;
        }
        else if(description.length == 0)
        {
            description = document.title;
        }
        else
        {
            description = description.innerHTML.replace(/(<([^>]+)>)/ig,"");;
        }
        
        if(imageUrl == null)
        {
            imageUrl = '/images/sectionicon_company.gif';
        }
        
        if(title.length > 100)
        {
            title = title.substring(0, 97) + "...";
        }
        
        if(description.length > 250)
        {
            description = description.substring(0, 247) + "...";
        }
        
        options.data = {
            "title": title,
            "url": location.pathname,
            "image-url": imageUrl,
            "description": description
        };
        
        $.ajax(options);
        
        return false;
    });
    
    // searches
    var searchesOptions = {};
    searchesOptions.url = ServicesPath + 'AddUserSearches.ajax';
    searchesOptions.type = 'POST';
    searchesOptions.success = function() {
        alert('Search results saved');
    }
    
    $('.add-search').click(function() {
        var title = 'Search: ' + $('#query').attr('value');
        
        if(title.length > 100)
        {
            title = title.substring(0, 97) + "...";
        }
        
        searchesOptions.data = {
            "title": title,
            "url": location.pathname + location.search
        };
        
        $.ajax(searchesOptions);
        
    });
});


