function printPage() {
    window.print();
}

// Val - string to be paded
// ch - padding character
// num - number of characters for padding
function padLeft(val, ch, num) {
    if (val == '') { return '' }
    var re = new RegExp(".{" + num + "}$");
    var pad = "";
    do {
        pad += ch;
    }
    while (pad.length < num)

    return re.exec(pad + val);
}

// Itemize characters to remove
function cleanString(str) {
    return str.replace(/[\(\)\.\-\s,]/g, "");
}
// Remove all non-digits
function cleanString(str) {
    return str.replace(/[^\d]/g, "");
}

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
}
String.prototype.ltrim = function() {
    return this.replace(/^\s+/g, "");
}
String.prototype.rtrim = function() {
    return this.replace(/\s+$/g, "");
}

function insertNthChar(string, chr, nth) {
    var output = '';
    for (var i = 0; i < string.length; i++) {
        if (i > 0 && i % 4 == 0)
            output += chr;
        output += string.charAt(i);
    }
    return output;
}

function testCreditCard() {
    myCardNo = document.getElementById('<%= CreditcardNumberClientID %>').value;
    myCardType = '<%=CreditCardType %>';
    if (checkCreditCard(myCardNo, myCardType)) {
        alert("Credit card has a valid format")
    }
    else {
        alert(ccErrors[ccErrorNo]);
        return false; // should uncomment this for real site, commented for testing purposes
    };
}

function LaunchWindow(vAction) {
    remotewin = window.open('http://www.abc.com/index.cfm?fuseaction=' + vAction, 'remotewin', 'width=245,height=190,resizable=0,scrollbars=0,top=200,left=200');
    if (remotewin != null) {
        if (remotewin.opener == null) {
            remotewin.opener = self;
        }
    }
}

// Code for docked ajax progress
var offsetfromedge = 0      //offset from window edge when content is "docked". Change if desired.
var dockarray = new Array() //array to cache dockit instances
var dkclear = new Array()   //array to cache corresponding clearinterval pointers

function dockit(el, duration) {
    this.source = document.all ? document.all[el] : document.getElementById(el);
    this.source.height = this.source.offsetHeight;
    this.docheight = truebody().clientHeight;
    this.duration = duration;
    this.pagetop = 0;
    this.elementoffset = this.getOffsetY();
    dockarray[dockarray.length] = this;
    var pointer = eval(dockarray.length - 1);
    var dynexpress = 'dkclear[' + pointer + ']=setInterval("dockornot(dockarray[' + pointer + '])",100);';
    dynexpress = (this.duration > 0) ? dynexpress + 'setTimeout("clearInterval(dkclear[' + pointer + ']); dockarray[' + pointer + '].source.style.top=0", duration*1000)' : dynexpress;
    eval(dynexpress);
}

dockit.prototype.getOffsetY = function() {
    var totaloffset = parseInt(this.source.offsetTop);
    var parentEl = this.source.offsetParent;
    while (parentEl != null) {
        totaloffset += parentEl.offsetTop;
        parentEl = parentEl.offsetParent;
    }
    return totaloffset;
}

function dockornot(obj) {
    obj.pagetop = truebody().scrollTop;
    if (obj.pagetop > obj.elementoffset) //detect upper offset
        obj.source.style.top = obj.pagetop - obj.elementoffset + offsetfromedge + "px";
    else if (obj.pagetop + obj.docheight < obj.elementoffset + parseInt(obj.source.height)) //lower offset
        obj.source.style.top = obj.pagetop + obj.docheight - obj.source.height - obj.elementoffset - offsetfromedge + "px";
    else
        obj.source.style.top = 0;
}

function truebody() {
    return (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body
}

// setting up Creuna namespaces
if (typeof Creuna == "undefined") {
    var Creuna = {};
}

if (typeof Creuna.Events == "undefined") {
    Creuna.Events = {};
}

Creuna.Events =
{
    addListener: function(obj, name, callback) {
        if (typeof obj.addEventListener != "undefined") {
            obj.addEventListener(name, callback, false);
        }
        else if (typeof window.attachEvent != "undefined") {
            obj.attachEvent("on" + name, callback);
        }
        else {
            var prop = "on" + name;
            var old = obj[prop];
            if (typeof obj[prop] != "function") {
                obj[prop] = callback;
            }
            else {
                obj[prop] = function() { old(); callback(); }
            }
        }
    }
}

if (typeof Creuna.Vacasol == "undefined") {
    Creuna.Vacasol = {};
}

// defining the Stats namespace
Creuna.Vacasol.Stats =
{
    // add triggerSearchFilter function to ajax post-back event handler
    initialize: function() {
        var requestManager = Sys.WebForms.PageRequestManager.getInstance();
        requestManager.add_initializeRequest(Creuna.Vacasol.Stats.triggerSearchFilter);
        //requestManager.add_endRequest(...?);
    },

    // Sends a request to google analytics indicating what filter function was used (in post back): /filter/search/[function]-[value]
    // Note: [function] can be the name of a function, or a control GUID combinded with the html label of the control (language versioned)
    //       [value] can be the selected value, or the GUID value combined with the current browser text selected (language versioned)
    triggerSearchFilter: function(sender, args) {
        // check for globally defined Google Analytics "pageTracker" variable
        if (typeof (pageTracker) == "undefined" || !pageTracker._trackPageview) {
            return false;
        }

        // get event-triggering element
        var element = args.get_postBackElement();

        if (element.nodeName != "INPUT" && element.nodeName != "SELECT") {
            // we're only interested in handling <input type="checkbox"> and <select>-boxes
            // (not <a> post-backs for instance)
            return false;
        }

        // define a few helper functions
        var helper =
	    {
	        // return the innerHTML of the <label> element that corresponds to the element provided
	        getLabel: function(element) {
	            if (!element.id) {
	                return;
	            }

	            var labelTags = document.getElementsByTagName("LABEL");
	            for (var i = 0; i < labelTags.length; i++) {
	                var names = [];
	                for (var n in labelTags[i])
	                    names.push(n);
	                names.sort();
	                var htmlForId = (labelTags[i].htmlFor ? labelTags[i].htmlFor : labelTags[i].getAttribute("for"));
	                if (htmlForId == element.id) {
	                    return labelTags[i].innerHTML;
	                }
	            }
	        },

	        // get last (semi-unique) section of a GUID (separated by -)
	        getShortGuid: function(guid) {
	            var parts = (new String(guid)).split("-");
	            return parts[parts.length - 1];
	        },

	        // get the last part of an id (separated by _)
	        getControlId: function(dotNetId) {
	            var parts = (new String(dotNetId)).split("_");
	            return parts[parts.length - 1];
	        }
	    }

        // collect stats info:
        //     map .net user control ID (or part of it, or GUID) 
        //     to something that can be understood and not be language dependant
        var filterFunctions =
	    {
	        /*		    "ddlCountry": "country",
	        "ddlRegion": "region",
	        "ddlSubRegion": "subRegion",*/
	        "ddlDaysToStay": "daysToStay",
	        "ddlNumOfPersons": "numberOfPersons",
	        "dtArrivalDate": "arrivalDate",
	        "ddlNumPrPage": "housesPerPage",
	        "ddlSortOrder": "sortOrder",
	        "ddlSortResults": "sortCriteria"
	    }

        // collect info about the selected control and value
        var label = helper.getLabel(element);
        var guid = helper.getControlId(element.id);
        var id = helper.getShortGuid(guid);
        if (filterFunctions[id]) {
            id = filterFunctions[id];
        }
        else if (label) {
            id += "[" + label + "]";
        }

        // prepare google analytics request (url)
        var text = element.value;
        if (element.type == "checkbox") {
            text = element.checked ? "yes" : "no";
        }
        else if (element.type == "select-one") {
            text = element.options[element.selectedIndex].text;
            text = helper.getShortGuid(element.value) + "[" + text + "]";
        }

        var url = "/filter/search/" + id + "-" + text.replace(/[\/\- ]/g, " ");
        pageTracker._trackPageview(url);
        //alert(url);
    },

    // just a default error handled wrapper for google analytics page hits
    triggerPageView: function(url) {
        // check for globally defined Google Analytics "pageTracker" variable
        if (typeof (pageTracker) == "undefined" || !pageTracker._trackPageview) {
            return false;
        }

        pageTracker._trackPageview(url);
    }
}

/* used on the object details page, to show/hide longer descriptions */
var objectDetailsToggleReadMoreShowHide = 'hide';
function objectDetailsToggleReadMore() {
    var readMoreLink = document.getElementById('readMoreLink');
    var readMoreFullText = document.getElementById('readMoreFullText');
    if (objectDetailsToggleReadMoreShowHide == 'hide') {
        objectDetailsToggleReadMoreShowHide = 'show';
        readMoreLink.style.display = 'none';
        readMoreFullText.style.display = 'inline';
    }
    else {
        objectDetailsToggleReadMoreShowHide = 'hide';
        readMoreLink.style.display = 'inline';
        readMoreFullText.style.display = 'none';
    }

    return false;
}

// NOTE: onRegionRequest moved to Default_v2.aspx


function str_replace(search, replace, subject) {
    var f = search, r = replace, s = subject;
    var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;

    while (j = 0, i--) {
        if (s[i]) {
            while (s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f) { };
        }
    };

    return sa ? s : s[0];
}

// MoodalBox popup handling
/*
function preparePopupLinks()
{
// add "popup=true" for MOOdalBox links
Window.onDomReady(function()
{
$A($$('a')).each(function(el)
{
// make all target="_blank" links into modal popups
if(el.href && el.target == "_blank")
{
var url = el.href;

// if external url, then use ContentRedirect.aspx to parse contents
if (url.indexOf('http') == 0)
{
url = str_replace('http://', '', url);
url = str_replace('?', '%3F', url);
url = str_replace('/', '%2f', url);
url = "ContentRedirect.aspx?url="+ url;
}

el.href = url;
                
url += (el.href.indexOf("?") == -1 ? "?" : "&")+"popup=true"; // query string handled by standard page template (change of master page)
		  
el.href = url;
		        
el.target = ""; // remove old target; not needed
el.rel = "moodalbox"; // this attirbute is handled by moodalbox.js
}
}, this);
});
}
*/

function configureMoodalBox() {
    var width = 500;
    var height = 300;

    // override moodalbox options
    _RESIZE_DURATION = 0; 		// Duration of height and width resizing (ms)
    _INITIAL_WIDTH = width; 	// Initial width of the box (px)
    _INITIAL_HEIGHT = height; 	// Initial height of the box (px)
    _CONTENTS_WIDTH = width; 	// Actual width of the box (px)
    _CONTENTS_HEIGHT = height; 	// Actual height of the box (px)
    _DEF_CONTENTS_WIDTH = width; 	// Default width of the box (px) - used for resetting when a different setting was used
    _DEF_CONTENTS_HEIGHT = height; 	// Default height of the box (px) - used for resetting when a different setting was used
    _ANIMATE_CAPTION = false; 	// Enable/Disable caption animation
    _EVAL_SCRIPTS = false; // Option to evaluate scripts in the response text
    _EVAL_RESPONSE = false; // Option to evaluate the whole response text

    // hack: override build in opacity of popup background
    eval("MOOdalBox.open = " + MOOdalBox.open.toString().replace(/\(0\.8\)/, "(0.3)"));

    // hack: insert close event handler
    eval("MOOdalBox.close = " + MOOdalBox.close.toString().replace(/{/, "{closePopup();"));
}

// called when moodal popup closes
function closePopup() {
    // reset popup contents (remove inner asp.net form tag, primarily)
    $get("mb_contents").innerHTML = "";
}

/* checks the personal data form on step 2 of the booking flow.
returns true if everything is ok, false otherwise. */
function checkPersonalData() {
    var errorBox = document.getElementById("personalDataError");

    var firstName = document.getElementById("ctl00_cphStageRegion_cphMainRegion_txtFirstName");
    var lastName = document.getElementById("ctl00_cphStageRegion_cphMainRegion_txtLastName");
    var address = document.getElementById("ctl00_cphStageRegion_cphMainRegion_txtAddress");
    var zipCode = document.getElementById("ctl00_cphStageRegion_cphMainRegion_txtZipCode");
    var city = document.getElementById("ctl00_cphStageRegion_cphMainRegion_txtCity");
    var country = document.getElementById("ctl00_cphStageRegion_cphMainRegion_ddlCountry");
    var otherCountry = document.getElementById("ctl00_cphStageRegion_cphMainRegion_txtOtherCountry");
    var phone = document.getElementById("ctl00_cphStageRegion_cphMainRegion_txtPhone");
    var mobilePhone = document.getElementById("ctl00_cphStageRegion_cphMainRegion_txtCellPhone");
    var email = document.getElementById("ctl00_cphStageRegion_cphMainRegion_txtEmail");
    var acceptAgreement = document.getElementById("ctl00_cphStageRegion_cphMainRegion_chbAcceptAgreement");
    var personalDataCheckboxes = document.getElementById("personalDataCheckboxes");

    var firstNameError = document.getElementById("firstNameError");
    var lastNameError = document.getElementById("lastNameError");
    var addressError = document.getElementById("addressError");
    var zipCodeError = document.getElementById("zipCodeError");
    var cityError = document.getElementById("cityError");
    var countryError = document.getElementById("countryError");
    var emailError = document.getElementById("emailError");
    var agreementError = document.getElementById("agreementError");

    var errorHappened = false;

    firstNameError.style.display = "none";
    lastNameError.style.display = "none";
    addressError.style.display = "none";
    zipCodeError.style.display = "none";
    cityError.style.display = "none";
    countryError.style.display = "none";
    emailError.style.display = "none";
    agreementError.style.display = "none";

    firstName.className = "";
    lastName.className = "";
    address.className = "";
    zipCode.className = "zipCode";
    city.className = "city";
    country.className = "dropdown";
    otherCountry.className = "";
    phone.className = "";
    mobilePhone.className = "";
    email.className = "";
    acceptAgreement.className = "";
    personalDataCheckboxes.className = "personalData checkboxes";

    if (firstName.value == "") {
        errorHappened = true;
        firstNameError.style.display = "block";
        firstName.className = "error";
    }

    if (lastName.value == "") {
        errorHappened = true;
        lastNameError.style.display = "block";
        lastName.className = "error";
    }

    if (address.value == "") {
        errorHappened = true;
        addressError.style.display = "block";
        address.className = "error";
    }

    if (zipCode.value == "") {
        errorHappened = true;
        zipCodeError.style.display = "block";
        zipCode.className = "zipCode error";
    }

    if (city.value == "") {
        errorHappened = true;
        cityError.style.display = "block";
        city.className = "city error";
    }

    if (country.selectedIndex == 0 && otherCountry.value == "") {
        errorHappened = true;
        countryError.style.display = "block";
        country.className = "dropdown error";
    }

    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (!filter.test(email.value)) {
        errorHappened = true;
        emailError.style.display = "block";
        email.className = "error";
    }

    if (!acceptAgreement.checked) {
        errorHappened = true;
        agreementError.style.display = "block";
        personalDataCheckboxes.className = "personalData checkboxes error";
    }

    if (errorHappened) {
        errorBox.style.display = "block";
        return false;
    }

    return true;
}

function firefoxDefaultButtonFix() {
    aList = document.getElementsByTagName("a");

    for (var i = 0; i < aList.length; i++) {
        try {
            var anchor = aList[i];
            if (anchor && anchor.id && anchor.id == "")
                continue;

            // define a click function for firefox
            if (typeof (anchor.click) == "undefined") {
                anchor.click = function() {
                    try {
                        this.onclick();
                    }
                    catch (ex) { };
                    eval(this.href.replace("javascript:", ""));

                }
            }
        }
        catch (ex) { }
    }
}