﻿/// <reference path="~/scripts/jquery-1.4.2.min.js" />
/// <reference path="~/scripts/prototypes.js" />



// launch live bidding page in a new window
function launchLiveBidding(url) {
    window.open(url, '_blank', 'scrollbars=no,width=740,height=645');
}

// load printing dialog box
function printPageButton() {
    $('#printLink').click(function () {
        window.print();
        return false;
    });
}


// Serialise the form and add to the querystring - so that the search is recoverable if we use the back button. 
function AddSearchParametersToQuerystring(searchForm) {
    if (searchForm) {
        var url = searchForm.action;
        url += '?searchTerm=' + $('#searchTerm').val();
        searchForm.action = url;
    }
}


function SetCookie(name, value, daysTillExpiry, path) {

    var cookie = name + '=' + escape(value) + ';'
    if (daysTillExpiry) {
        var date = new Date();
        date.setDate(date.getDate() + daysTillExpiry);
        cookie += ' expires=' + date.toUTCString() + ';';
    }

    // Set path (defaults to '/' ; scope global to the site)
    cookie += ' path=' + (path || '/') + ';'

    document.cookie = cookie;
}


function GetCookie(name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(name + "=");
        if (c_start != -1) {
            c_start = c_start + name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

function DeleteCookie(name) {
    // Set cookie to expire yesterday - will get 
    SetCookie(name, '', -1);
}




//This builds the correct S3 name for image file
function S3ImageName(imagename, size) {

    var s3Size;
    switch (size) {
        case 'Thumbnail': s3Size = '55x55'; break;
        case 'Small': s3Size = '80x80'; break;
        case 'Medium': s3Size = '120x120'; break;
        case 'IBMedium': s3Size = '155x155'; break;
        case 'Large': s3Size = '468x382'; break;
        case 'IBLarge': s3Size = '540x360'; break;
        default: s3Size = '120x120';
    }

    var newName = imagename.substr(0, imagename.length - 4);
    newName += '_' + s3Size;
    newName += imagename.substr(imagename.length - 4, 4)

    return newName;
}

//call this method to validate the form on client side
function isFormValid(form) {
    var errors;
    if (form[0]['__MVC_FormValidation']) {
        errors = form[0]['__MVC_FormValidation'].validate("submit");        // Validate the form
    }
    if (!form[0]['__MVC_FormValidation'] || errors.length == 0) {
        return true;
    }
    return false;
}


function validateEmail(value) {
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    return emailPattern.test(value);
}


function validateKeyPress(jQueryEventObject, regularExpression) {
    var charCode = jQueryEventObject.charCode || jQueryEventObject.keyCode || jQueryEventObject.which;

    if (charCode == 8 || charCode == 13 || charCode == 27 || charCode == 37 || charCode == 39) {
        // allow backspace, return, escape, left, right
        return true;
    }
    else {
        // Check that the new character would be valid in the field
        var textIncludingNewCharacter = jQueryEventObject.target.value + String.fromCharCode(charCode);
        var pattern = new RegExp(regularExpression, "");
        var valid = pattern.test(textIncludingNewCharacter);
        return valid;
    }
}



function EstimateExists(lowEstimate, highEstimate) {
    return ((lowEstimate || 0) > 0) || ((highEstimate || 0) > 0);
}


// Returns string value for lot estimates    
function DisplayEstimates(lowEstimate, highEstimate, currencySymbol, currencyCode, notApplicable) {

    // must have a low or high estimate greater than 0
    if (EstimateExists(lowEstimate, highEstimate)) {

        var estimates = "";
        estimates += (currencySymbol || '');

        if (lowEstimate) {
            estimates += lowEstimate;
        }

        if (lowEstimate && highEstimate) estimates += " - ";

        if (highEstimate) {
            estimates += (currencySymbol || '');
            estimates += highEstimate;
        }

        if (currencyCode != 'GBP' && currencyCode != 'EUR') {
            estimates += ' ' + (currencyCode || '');
        }

        return estimates;
    }

    return notApplicable;
}

//call this method on image onerror event, to replace the non-existent image to a generic one
function ImageNotFound(imgElement, hrefElement) {
    $("#" + hrefElement).addClass("noImage");
    $("#" + imgElement).addClass("hide");
}


function AjaxWithDefaults(url, data, userOptions) {
    ///<summary>Wrapper for an ajax call, passes user's callbacks to DefaultAjaxSuccess and DefaultAjaxError callbacks </summary>
    var options = {
        type: 'POST',
        timeout: 100000,
        success: null,
        error: null
    };

    $.extend(options, userOptions);

    var SuccessFunction = function(response) { DefaultAjaxSuccess(response, options.success, options.error); };
    var ErrorFunction = function (response) { DefaultAjaxError(response, options.error); };

    $.ajax({
        type: options.type,
        url: url,
        data: data,
        success: SuccessFunction,
        error: ErrorFunction,
        timeout: options.timeout // 10 second timeout
    });
}



function DefaultAjaxSuccess(response, SuccessFunction, FailFunction) {
    ///<summary>Default sucess handler for an ajax call. Accepts user defined success and error callbacks.Callbacks should set response.prevent Default to prevent the default callback behaviour</summary>
    
    if (response.success) {

        // Run user defined callback first
        if (SuccessFunction) {
            SuccessFunction(response);
        }

        // if preventDefault is set in the user defined callback, stop here
        if (response.preventDefault) {
            return;
        }

        // show lightbox notification
        if (response.notification) {
            // Show a user message
            ShowNotification('success', '', response.notification);
        }

        // redirect
        if (response.redirect) {
            // Transfer to the returned location
            window.location.href = response.redirect;
        }

        // reload the current page
        if (response.reloadPage) {
            window.location.reload(true);
            document.location.reload(true);
        }
    }
    else {
        // Communication succeeded, but server operation failed
        DefaultAjaxError(response, FailFunction);
    }
}


function DefaultAjaxError(response, FailFunction) {
    ///<summary>Default error handler for an ajax call. Accepts a user defined callback </summary>
    
    // run user-defined callback
    if (FailFunction) {
        FailFunction(response);

        // if preventDefault is set in the user defined callback, stop here
        if (response.preventDefault) {
            return;
        }
    }

    // Show a notification indicating the response failed. 
    ShowNotification('error', '', response.notification || response.responseText || 'An Error occurred');
}




