/* JS Contents:
1st - Auxiliary Plugins
2nd Portal Functions
*/

// Auxiliary Plugins
/* -------------------------------------------------- *
* ToggleVal 2.1
* Updated: 1/16/09
* -------------------------------------------------- *
* Author: Aaron Kuzemchak
* URL: http://aaronkuzemchak.com/
* Copyright: 2008-2009 Aaron Kuzemchak
* License: MIT License
** -------------------------------------------------- */

(function ($) { $.fn.toggleVal = function (theOptions) { if (!theOptions || typeof (theOptions) == "object") { theOptions = $.extend({ focusClass: "tv-focused", changedClass: "tv-changed", populateFrom: "default", text: null, removeLabels: false }, theOptions) } else if (typeof (theOptions) == "string" && theOptions.toLowerCase() == "destroy") { var destroy = true } return this.each(function () { if (destroy) { $(this).unbind("focus.toggleval").unbind("blur.toggleval").removeData("defText"); return false } var defText = ""; switch (theOptions.populateFrom) { case "alt": defText = $(this).attr("alt"); $(this).val(defText); break; case "label": defText = $("label[for='" + $(this).attr("id") + "']").text(); $(this).val(defText); break; case "custom": defText = theOptions.text; $(this).val(defText); break; default: defText = $(this).val() } $(this).addClass("toggleval").data("defText", defText); if (theOptions.removeLabels == true) { $("label[for='" + $(this).attr("id") + "']").remove() } $(this).bind("focus.toggleval", function () { if ($(this).val() == $(this).data("defText")) { $(this).val("") } $(this).addClass(theOptions.focusClass).removeClass(theOptions.changedClass) }).bind("blur.toggleval", function () { if ($(this).val() == "") { $(this).val($(this).data("defText")) } $(this).removeClass(theOptions.focusClass); if ($(this).val() != $(this).data("defText")) { $(this).addClass(theOptions.changedClass) } else { $(this).removeClass(theOptions.changedClass) } }) }) } })(jQuery);


/*
jqURL
by Josh Nathanson

various manipulations on url strings and windows.  
all functions can also take a window object as an argument,
for example {win:opener}
but will default to current window if none is passed.

public functions:

-------------------------
.url({ 
win:window object 
})
-------------------------
returns the whole url string
like win.location.href

so if the current window href is "http://www.mysite.com?var1=1&var2=2&var3=3"
	
$.jqURL.url() returns "http://www.mysite.com?var1=1&var2=2&var3=3"
	
	
------------------------------
.loc(urlstr:string, 
{ 
win:window object, 
w:integer, 
h:integer, 
t:integer,
l:integer,
wintype:string('_top'[default],'_blank','_parent') )
})
------------------------------																			 
- directs passed in window to urlstr, which is required
- works like window.location.href = 'myurl'
- but you can also use it to pop open a new window by passing in "_blank" as the wintype
- if popping open a window, defaults to center of screen

so
$.jqURL.loc('http://www.google.com',
{w:200,h:200,wintype:'_blank'});
would open Google in a new centered 200x200 window
	
or, locate an url to any named window:
$.jqURL.loc('http://www.google.com',{ win:mywindow });
opens Google in mywindow


------------------------------
.qs({ 
ret:string('string'[default],'object'), 
win:window object })
------------------------------
returns querystring, either string (pass ret:'string' [default])
or object (pass ret:'object') 

so if the current window href is "http://www.mysite.com?var1=1&var2=2&var3=3"

$.jqURL.qs();
returns "var1=1&var2=2&var3=3"
	
$.jqURL.qs({ ret:'object' });
returns Object var1=1,var2=2,var3=3


------------------------------
.strip({ keys:string(list of keys to strip), win:window object })
------------------------------
if passed with no arguments, returns url with '?' and query string removed
if you pass in list of keys, it returns url with the specified key-value pairs removed

so if the current window href is "http://www.mysite.com?var1=1&var2=2&var3=3"

$.jqURL.strip();
will return
"http://www.mysite.com"
	
$.jqURL.strip({ keys:'var1,var2' });
will return
"http://www.mysite.com?var3=3"
	
	
-------------------------------------
.get(key, {win:window object})
-------------------------------------
returns value of passed in querystring key

so if the current window href is "http://www.mysite.com?var1=1&var2=2&var3=3"
$.jqURL.get('var2');
will return 2

--------------------------------------
.set(hash, {win:window object})
--------------------------------------
returns the window's url, but with the keys/values set in the query string
if the keys already exist, re-sets the value
if they don't exist, they're appended onto the query string

*/

jQuery.jqURL = {

    url: // returns a string
	function (args) {
	    args =
			jQuery.extend({
			    win: window
			},
			args);
	    return args.win.location.href;
	},

    loc:
	function (urlstr, args) {
	    args =
			jQuery.extend({
			    win: window,
			    w: 500,
			    h: 500,
			    wintype: '_top'
			},
			args);

	    if (!args.t) {
	        args.t = screen.height / 2 - args.h / 2;
	    }
	    if (!args.l) {
	        args.l = screen.width / 2 - args.w / 2;
	    }
	    if (args['wintype'] == '_top') {
	        args.win.location.href = urlstr;
	    }
	    else {
	        open(
			urlstr,
			args['wintype'],
			'width=' + args.w + ',height=' + args.h + ',top=' + args.t + ',left=' + args.l + ',scrollbars,resizable'
			);

	    }
	    return;
	},

    qs:
	function (args) {
	    args = jQuery.extend({
	        ret: 'string',
	        win: window
	    },
		args);

	    if (args['ret'] == 'string') {
	        return jQuery.jqURL.url({ win: args.win }).split('?')[1];
	    }

	    else if (args['ret'] == 'object') {

	        var qsobj = {};
	        var thisqs = jQuery.jqURL.url({ win: args.win }).split('?')[1];

	        if (thisqs) {
	            var pairs = thisqs.split('&');
	            for (i = 0; i < pairs.length; i++) {
	                var pair = pairs[i].split('=');
	                qsobj[pair[0]] = pair[1];
	            }
	        }
	        return qsobj;
	    }
	},

    strip:
	function (args) {
	    args = jQuery.extend({
	        keys: '',
	        win: window
	    },
			args);

	    if (jQuery.jqURL.url().indexOf('?') == -1) { // no query string found
	        return jQuery.jqURL.url({ win: args.win });
	    }
	    // if no keys passed in, just return url with no querystring
	    else if (!args.keys) {
	        return jQuery.jqURL.url({ win: args.win }).split('?')[0];
	    }
	    else { //return stripped url

	        var qsobj = jQuery.jqURL.qs({ ret: 'object', win: args.win });  // object with key/value pairs		
	        var counter = 0;
	        var url = jQuery.jqURL.url({ win: args.win }).split('?')[0] + '?';
	        var amp = '';

	        for (var key in qsobj) {
	            if (args.keys.indexOf(key) == -1) {
	                // pass test, add this key/value to string
	                amp = (counter) ? '&' : '';
	                url = url + amp + key + '=' + qsobj[key];
	                counter++;
	            }
	        }
	        return url;
	    }
	},

    get:
	function (key, args) {
	    args = jQuery.extend({
	        win: window
	    }, args);

	    qsobj = jQuery.jqURL.qs({ ret: 'object', win: args.win });
	    return qsobj[key];
	},

    set:
	function (hash, args) {
	    args = jQuery.extend({
	        win: window
	    }, args);

	    // get current querystring
	    var qsobj = jQuery.jqURL.qs({ ret: 'object', win: args.win });

	    // add/set values from hash
	    for (var i in hash) {
	        qsobj[i] = hash[i];
	    }

	    var qstring = '';
	    var counter = 0;
	    var amp = '';

	    // turn qsobj into string
	    for (var k in qsobj) {
	        amp = (counter) ? '&' : '';
	        qstring = qstring + amp + k + '=' + qsobj[k];
	        counter++;
	    }
	    return jQuery.jqURL.strip({ win: args.win }) + '?' + qstring;
	}

};

/**
* jQuery.ScrollTo - Easy element scrolling using jQuery.
* Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
* Dual licensed under MIT and GPL.
* Date: 5/25/2009
* @author Ariel Flesler
* @version 1.4.2
*
* http://flesler.blogspot.com/2007/10/jqueryscrollto.html
*/
; (function (d) { var k = d.scrollTo = function (a, i, e) { d(window).scrollTo(a, i, e) }; k.defaults = { axis: 'xy', duration: parseFloat(d.fn.jquery) >= 1.3 ? 0 : 1 }; k.window = function (a) { return d(window)._scrollable() }; d.fn._scrollable = function () { return this.map(function () { var a = this, i = !a.nodeName || d.inArray(a.nodeName.toLowerCase(), ['iframe', '#document', 'html', 'body']) != -1; if (!i) return a; var e = (a.contentWindow || a).document || a.ownerDocument || a; return d.browser.safari || e.compatMode == 'BackCompat' ? e.body : e.documentElement }) }; d.fn.scrollTo = function (n, j, b) { if (typeof j == 'object') { b = j; j = 0 } if (typeof b == 'function') b = { onAfter: b }; if (n == 'max') n = 9e9; b = d.extend({}, k.defaults, b); j = j || b.speed || b.duration; b.queue = b.queue && b.axis.length > 1; if (b.queue) j /= 2; b.offset = p(b.offset); b.over = p(b.over); return this._scrollable().each(function () { var q = this, r = d(q), f = n, s, g = {}, u = r.is('html,body'); switch (typeof f) { case 'number': case 'string': if (/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)) { f = p(f); break } f = d(f, this); case 'object': if (f.is || f.style) s = (f = d(f)).offset() } d.each(b.axis.split(''), function (a, i) { var e = i == 'x' ? 'Left' : 'Top', h = e.toLowerCase(), c = 'scroll' + e, l = q[c], m = k.max(q, i); if (s) { g[c] = s[h] + (u ? 0 : l - r.offset()[h]); if (b.margin) { g[c] -= parseInt(f.css('margin' + e)) || 0; g[c] -= parseInt(f.css('border' + e + 'Width')) || 0 } g[c] += b.offset[h] || 0; if (b.over[h]) g[c] += f[i == 'x' ? 'width' : 'height']() * b.over[h] } else { var o = f[h]; g[c] = o.slice && o.slice(-1) == '%' ? parseFloat(o) / 100 * m : o } if (/^\d+$/.test(g[c])) g[c] = g[c] <= 0 ? 0 : Math.min(g[c], m); if (!a && b.queue) { if (l != g[c]) t(b.onAfterFirst); delete g[c] } }); t(b.onAfter); function t(a) { r.animate(g, j, b.easing, a && function () { a.call(this, n, b) }) } }).end() }; k.max = function (a, i) { var e = i == 'x' ? 'Width' : 'Height', h = 'scroll' + e; if (!d(a).is('html,body')) return a[h] - d(a)[e.toLowerCase()](); var c = 'client' + e, l = a.ownerDocument.documentElement, m = a.ownerDocument.body; return Math.max(l[h], m[h]) - Math.min(l[c], m[c]) }; function p(a) { return typeof a == 'object' ? a : { top: a, left: a} } })(jQuery);

/*
* --------------------------------------------------------------------
* jQuery-Plugin - selectToUISlider - creates a UI slider component from a select element(s)
* by Scott Jehl, scott@filamentgroup.com
* http://www.filamentgroup.com
* reference article: http://www.filamentgroup.com/lab/update_jquery_ui_16_slider_from_a_select_element/
* demo page: http://www.filamentgroup.com/examples/slider_v2/index.html
* 
* Copyright (c) 2008 Filament Group, Inc
* Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
*
* Usage Notes: please refer to our article above for documentation
*  
* --------------------------------------------------------------------
*/


jQuery.fn.selectToUISlider = function (settings) {
    var selects = jQuery(this);

    //accessible slider options
    var options = jQuery.extend({
        labels: 3, //number of visible labels
        tooltip: true, //show tooltips, boolean
        tooltipSrc: 'text', //accepts 'value' as well
        labelSrc: 'value', //accepts 'value' as well	,
        sliderOptions: null,
        cssClass: ''

    }, settings);


    //handle ID attrs - selects each need IDs for handles to find them
    var handleIds = (function () {
        var tempArr = [];
        selects.each(function () {
            tempArr.push('handle_' + jQuery(this).attr('id'));
        });
        return tempArr;
    })();

    //array of all option elements in select element (ignores optgroups)
    var selectOptions = (function () {
        var opts = [];
        selects.eq(0).find('option').each(function () {
            opts.push({
                value: jQuery(this).attr('value'),
                text: jQuery(this).text()
            });
        });
        return opts;
    })();

    //array of opt groups if present
    var groups = (function () {
        if (selects.eq(0).find('optgroup').size() > 0) {
            var groupedData = [];
            selects.eq(0).find('optgroup').each(function (i) {
                groupedData[i] = {};
                groupedData[i].label = jQuery(this).attr('label');
                groupedData[i].options = [];
                jQuery(this).find('option').each(function () {
                    groupedData[i].options.push({ text: jQuery(this).text(), value: jQuery(this).attr('value') });
                });
            });
            return groupedData;
        }
        else return null;
    })();

    //check if obj is array
    function isArray(obj) {
        return obj.constructor == Array;
    }
    //return tooltip text from option index
    function ttText(optIndex) {
        return (options.tooltipSrc == 'text') ? selectOptions[optIndex].text : selectOptions[optIndex].value;
    }

    //plugin-generated slider options (can be overridden)
    var sliderOptions = {
        step: 1,
        min: 0,
        orientation: 'horizontal',
        max: selectOptions.length - 1,
        range: selects.length > 1, //multiple select elements = true
        slide: function (e, ui) {//slide function
            var thisHandle = jQuery(ui.handle);
            //handle feedback 
            var textval = ttText(ui.value);
            thisHandle
					.attr('aria-valuetext', textval)
					.attr('aria-valuenow', ui.value)
					.find('.ui-slider-tooltip .ttContent')
						.text(textval);

            //control original select menu
            var currSelect = jQuery('#' + thisHandle.attr('id').split('handle_')[1]);
            currSelect.find('option').eq(ui.value).attr('selected', 'selected');
        },
        change: null,
        values: (function () {
            var values = [];
            selects.each(function () {
                values.push(jQuery(this).get(0).selectedIndex);
            });
            return values;
        })()
    };

    //slider options from settings
    options.sliderOptions = (settings) ? jQuery.extend(sliderOptions, settings.sliderOptions) : sliderOptions;

    //select element change event	
    selects.bind('change keyup click', function () {
        var thisIndex = jQuery(this).get(0).selectedIndex;
        var thisHandle = jQuery('#handle_' + jQuery(this).attr('id'));
        var handleIndex = thisHandle.data('handleNum');
        thisHandle.parents('.ui-slider:eq(0)').slider("values", handleIndex, thisIndex);
    });


    //create slider component div
    var sliderComponent = jQuery('<div class="' + options.cssClass + '"></div>');

    //CREATE HANDLES
    selects.each(function (i) {
        var hidett = '';

        //associate label for ARIA
        var thisLabel = jQuery('label[for=' + jQuery(this).attr('id') + ']');
        //labelled by aria doesn't seem to work on slider handle. Using title attr as backup
        var labelText = (thisLabel.size() > 0) ? 'Slider control for ' + thisLabel.text() + '' : '';
        var thisLabelId = thisLabel.attr('id') || thisLabel.attr('id', 'label_' + handleIds[i]).attr('id');


        if (options.tooltip == false) { hidett = ' style="display: none;"'; }
        jQuery('<a ' +
				'href="#" tabindex="0" ' +
				'id="' + handleIds[i] + '" ' +
				'class="ui-slider-handle" ' +
				'role="slider" ' +
				'aria-labelledby="' + thisLabelId + '" ' +
				'aria-valuemin="' + options.sliderOptions.min + '" ' +
				'aria-valuemax="' + options.sliderOptions.max + '" ' +
				'aria-valuenow="' + options.sliderOptions.values[i] + '" ' +
				'aria-valuetext="' + ttText(options.sliderOptions.values[i]) + '" ' +
			'><span class="screenReaderContext">' + labelText + '</span>' +
			'<span class="ui-slider-tooltip ui-widget-content ui-corner-all"' + hidett + '><span class="ttContent"></span>' +
				'<span class="ui-tooltip-pointer-down ui-widget-content"><span class="ui-tooltip-pointer-down-inner"></span></span>' +
			'</span></a>')
			.data('handleNum', i)
			.appendTo(sliderComponent);
    });

    //CREATE SCALE AND TICS

    //write dl if there are optgroups
    if (groups) {
        var inc = 0;
        var scale = sliderComponent.append('<dl class="ui-slider-scale ui-helper-reset" role="presentation"></dl>').find('.ui-slider-scale:eq(0)');
        jQuery(groups).each(function (h) {
            scale.append('<dt style="width: ' + (100 / groups.length).toFixed(2) + '%' + '; left:' + (h / (groups.length - 1) * 100).toFixed(2) + '%' + '"><span>' + this.label + '</span></dt>'); //class name becomes camelCased label
            var groupOpts = this.options;
            jQuery(this.options).each(function (i) {
                var style = (inc == selectOptions.length - 1 || inc == 0) ? 'style="display: none;"' : '';
                var labelText = (options.labelSrc == 'text') ? groupOpts[i].text : groupOpts[i].value;
                scale.append('<dd style="left:' + leftVal(inc) + '"><span class="ui-slider-label">' + labelText + '</span><span class="ui-slider-tic ui-widget-content"' + style + '></span></dd>');
                inc++;
            });
        });
    }
    //write ol
    else {
        var scale = sliderComponent.append('<ol class="ui-slider-scale ui-helper-reset" role="presentation"></ol>').find('.ui-slider-scale:eq(0)');
        jQuery(selectOptions).each(function (i) {
            var style = (i == selectOptions.length - 1 || i == 0) ? 'style="display: none;"' : '';
            var labelText = (options.labelSrc == 'text') ? this.text : this.value;
            scale.append('<li style="left:' + leftVal(i) + '"><span class="ui-slider-label">' + labelText + '</span><span class="ui-slider-tic ui-widget-content"' + style + '></span></li>');
        });
    }

    function leftVal(i) {
        return (i / (selectOptions.length - 1) * 100).toFixed(2) + '%';

    }




    //show and hide labels depending on labels pref
    //show the last one if there are more than 1 specified
    if (options.labels > 1) sliderComponent.find('.ui-slider-scale li:last span.ui-slider-label, .ui-slider-scale dd:last span.ui-slider-label').addClass('ui-slider-label-show');

    //set increment
    var increm = Math.max(1, Math.round(selectOptions.length / options.labels));
    //show em based on inc
    for (var j = 0; j < selectOptions.length; j += increm) {
        if ((selectOptions.length - j) > increm) {//don't show if it's too close to the end label
            sliderComponent.find('.ui-slider-scale li:eq(' + j + ') span.ui-slider-label, .ui-slider-scale dd:eq(' + j + ') span.ui-slider-label').addClass('ui-slider-label-show');
        }
    }

    //style the dt's
    sliderComponent.find('.ui-slider-scale dt').each(function (i) {
        jQuery(this).css({
            'left': ((100 / (groups.length)) * i).toFixed(2) + '%'
        });
    });


    //inject and return 
    sliderComponent
	.insertAfter(jQuery(this).eq(this.length - 1))
	.slider(options.sliderOptions)
	.attr('role', 'application')
	.find('.ui-slider-label')
	.each(function () {
	    jQuery(this).css('marginLeft', -jQuery(this).width() / 2);
	});

    //update tooltip arrow inner color
    sliderComponent.find('.ui-tooltip-pointer-down-inner').each(function () {
        var bWidth = jQuery('.ui-tooltip-pointer-down-inner').css('borderTopWidth');
        var bColor = jQuery(this).parents('.ui-slider-tooltip').css('backgroundColor')
        jQuery(this).css('border-top', bWidth + ' solid ' + bColor);
    });

    var values = sliderComponent.slider('values');

    if (isArray(values)) {
        jQuery(values).each(function (i) {
            sliderComponent.find('.ui-slider-tooltip .ttContent').eq(i).text(ttText(this));
        });
    }
    else {
        sliderComponent.find('.ui-slider-tooltip .ttContent').eq(0).text(ttText(values));
    }


    return this;
}


/*
* jQuery UI 1.7.1
*
* Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI
*/
jQuery.ui || (function (c) { var i = c.fn.remove, d = c.browser.mozilla && (parseFloat(c.browser.version) < 1.9); c.ui = { version: "1.7.1", plugin: { add: function (k, l, n) { var m = c.ui[k].prototype; for (var j in n) { m.plugins[j] = m.plugins[j] || []; m.plugins[j].push([l, n[j]]) } }, call: function (j, l, k) { var n = j.plugins[l]; if (!n || !j.element[0].parentNode) { return } for (var m = 0; m < n.length; m++) { if (j.options[n[m][0]]) { n[m][1].apply(j.element, k) } } } }, contains: function (k, j) { return document.compareDocumentPosition ? k.compareDocumentPosition(j) & 16 : k !== j && k.contains(j) }, hasScroll: function (m, k) { if (c(m).css("overflow") == "hidden") { return false } var j = (k && k == "left") ? "scrollLeft" : "scrollTop", l = false; if (m[j] > 0) { return true } m[j] = 1; l = (m[j] > 0); m[j] = 0; return l }, isOverAxis: function (k, j, l) { return (k > j) && (k < (j + l)) }, isOver: function (o, k, n, m, j, l) { return c.ui.isOverAxis(o, n, j) && c.ui.isOverAxis(k, m, l) }, keyCode: { BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108, NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38} }; if (d) { var f = c.attr, e = c.fn.removeAttr, h = "http://www.w3.org/2005/07/aaa", a = /^aria-/, b = /^wairole:/; c.attr = function (k, j, l) { var m = l !== undefined; return (j == "role" ? (m ? f.call(this, k, j, "wairole:" + l) : (f.apply(this, arguments) || "").replace(b, "")) : (a.test(j) ? (m ? k.setAttributeNS(h, j.replace(a, "aaa:"), l) : f.call(this, k, j.replace(a, "aaa:"))) : f.apply(this, arguments))) }; c.fn.removeAttr = function (j) { return (a.test(j) ? this.each(function () { this.removeAttributeNS(h, j.replace(a, "")) }) : e.call(this, j)) } } c.fn.extend({ remove: function () { c("*", this).add(this).each(function () { c(this).triggerHandler("remove") }); return i.apply(this, arguments) }, enableSelection: function () { return this.attr("unselectable", "off").css("MozUserSelect", "").unbind("selectstart.ui") }, disableSelection: function () { return this.attr("unselectable", "on").css("MozUserSelect", "none").bind("selectstart.ui", function () { return false }) }, scrollParent: function () { var j; if ((c.browser.msie && (/(static|relative)/).test(this.css("position"))) || (/absolute/).test(this.css("position"))) { j = this.parents().filter(function () { return (/(relative|absolute|fixed)/).test(c.curCSS(this, "position", 1)) && (/(auto|scroll)/).test(c.curCSS(this, "overflow", 1) + c.curCSS(this, "overflow-y", 1) + c.curCSS(this, "overflow-x", 1)) }).eq(0) } else { j = this.parents().filter(function () { return (/(auto|scroll)/).test(c.curCSS(this, "overflow", 1) + c.curCSS(this, "overflow-y", 1) + c.curCSS(this, "overflow-x", 1)) }).eq(0) } return (/fixed/).test(this.css("position")) || !j.length ? c(document) : j } }); c.extend(c.expr[":"], { data: function (l, k, j) { return !!c.data(l, j[3]) }, focusable: function (k) { var l = k.nodeName.toLowerCase(), j = c.attr(k, "tabindex"); return (/input|select|textarea|button|object/.test(l) ? !k.disabled : "a" == l || "area" == l ? k.href || !isNaN(j) : !isNaN(j)) && !c(k)["area" == l ? "parents" : "closest"](":hidden").length }, tabbable: function (k) { var j = c.attr(k, "tabindex"); return (isNaN(j) || j >= 0) && c(k).is(":focusable") } }); function g(m, n, o, l) { function k(q) { var p = c[m][n][q] || []; return (typeof p == "string" ? p.split(/,?\s+/) : p) } var j = k("getter"); if (l.length == 1 && typeof l[0] == "string") { j = j.concat(k("getterSetter")) } return (c.inArray(o, j) != -1) } c.widget = function (k, j) { var l = k.split(".")[0]; k = k.split(".")[1]; c.fn[k] = function (p) { var n = (typeof p == "string"), o = Array.prototype.slice.call(arguments, 1); if (n && p.substring(0, 1) == "_") { return this } if (n && g(l, k, p, o)) { var m = c.data(this[0], k); return (m ? m[p].apply(m, o) : undefined) } return this.each(function () { var q = c.data(this, k); (!q && !n && c.data(this, k, new c[l][k](this, p))._init()); (q && n && c.isFunction(q[p]) && q[p].apply(q, o)) }) }; c[l] = c[l] || {}; c[l][k] = function (o, n) { var m = this; this.namespace = l; this.widgetName = k; this.widgetEventPrefix = c[l][k].eventPrefix || k; this.widgetBaseClass = l + "-" + k; this.options = c.extend({}, c.widget.defaults, c[l][k].defaults, c.metadata && c.metadata.get(o)[k], n); this.element = c(o).bind("setData." + k, function (q, p, r) { if (q.target == o) { return m._setData(p, r) } }).bind("getData." + k, function (q, p) { if (q.target == o) { return m._getData(p) } }).bind("remove", function () { return m.destroy() }) }; c[l][k].prototype = c.extend({}, c.widget.prototype, j); c[l][k].getterSetter = "option" }; c.widget.prototype = { _init: function () { }, destroy: function () { this.element.removeData(this.widgetName).removeClass(this.widgetBaseClass + "-disabled " + this.namespace + "-state-disabled").removeAttr("aria-disabled") }, option: function (l, m) { var k = l, j = this; if (typeof l == "string") { if (m === undefined) { return this._getData(l) } k = {}; k[l] = m } c.each(k, function (n, o) { j._setData(n, o) }) }, _getData: function (j) { return this.options[j] }, _setData: function (j, k) { this.options[j] = k; if (j == "disabled") { this.element[k ? "addClass" : "removeClass"](this.widgetBaseClass + "-disabled " + this.namespace + "-state-disabled").attr("aria-disabled", k) } }, enable: function () { this._setData("disabled", false) }, disable: function () { this._setData("disabled", true) }, _trigger: function (l, m, n) { var p = this.options[l], j = (l == this.widgetEventPrefix ? l : this.widgetEventPrefix + l); m = c.Event(m); m.type = j; if (m.originalEvent) { for (var k = c.event.props.length, o; k; ) { o = c.event.props[--k]; m[o] = m.originalEvent[o] } } this.element.trigger(m, n); return !(c.isFunction(p) && p.call(this.element[0], m, n) === false || m.isDefaultPrevented()) } }; c.widget.defaults = { disabled: false }; c.ui.mouse = { _mouseInit: function () { var j = this; this.element.bind("mousedown." + this.widgetName, function (k) { return j._mouseDown(k) }).bind("click." + this.widgetName, function (k) { if (j._preventClickEvent) { j._preventClickEvent = false; k.stopImmediatePropagation(); return false } }); if (c.browser.msie) { this._mouseUnselectable = this.element.attr("unselectable"); this.element.attr("unselectable", "on") } this.started = false }, _mouseDestroy: function () { this.element.unbind("." + this.widgetName); (c.browser.msie && this.element.attr("unselectable", this._mouseUnselectable)) }, _mouseDown: function (l) { l.originalEvent = l.originalEvent || {}; if (l.originalEvent.mouseHandled) { return } (this._mouseStarted && this._mouseUp(l)); this._mouseDownEvent = l; var k = this, m = (l.which == 1), j = (typeof this.options.cancel == "string" ? c(l.target).parents().add(l.target).filter(this.options.cancel).length : false); if (!m || j || !this._mouseCapture(l)) { return true } this.mouseDelayMet = !this.options.delay; if (!this.mouseDelayMet) { this._mouseDelayTimer = setTimeout(function () { k.mouseDelayMet = true }, this.options.delay) } if (this._mouseDistanceMet(l) && this._mouseDelayMet(l)) { this._mouseStarted = (this._mouseStart(l) !== false); if (!this._mouseStarted) { l.preventDefault(); return true } } this._mouseMoveDelegate = function (n) { return k._mouseMove(n) }; this._mouseUpDelegate = function (n) { return k._mouseUp(n) }; c(document).bind("mousemove." + this.widgetName, this._mouseMoveDelegate).bind("mouseup." + this.widgetName, this._mouseUpDelegate); (c.browser.safari || l.preventDefault()); l.originalEvent.mouseHandled = true; return true }, _mouseMove: function (j) { if (c.browser.msie && !j.button) { return this._mouseUp(j) } if (this._mouseStarted) { this._mouseDrag(j); return j.preventDefault() } if (this._mouseDistanceMet(j) && this._mouseDelayMet(j)) { this._mouseStarted = (this._mouseStart(this._mouseDownEvent, j) !== false); (this._mouseStarted ? this._mouseDrag(j) : this._mouseUp(j)) } return !this._mouseStarted }, _mouseUp: function (j) { c(document).unbind("mousemove." + this.widgetName, this._mouseMoveDelegate).unbind("mouseup." + this.widgetName, this._mouseUpDelegate); if (this._mouseStarted) { this._mouseStarted = false; this._preventClickEvent = (j.target == this._mouseDownEvent.target); this._mouseStop(j) } return false }, _mouseDistanceMet: function (j) { return (Math.max(Math.abs(this._mouseDownEvent.pageX - j.pageX), Math.abs(this._mouseDownEvent.pageY - j.pageY)) >= this.options.distance) }, _mouseDelayMet: function (j) { return this.mouseDelayMet }, _mouseStart: function (j) { }, _mouseDrag: function (j) { }, _mouseStop: function (j) { }, _mouseCapture: function (j) { return true } }; c.ui.mouse.defaults = { cancel: null, distance: 1, delay: 0} })(jQuery); ; /*
 * jQuery UI Slider 1.7.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Slider
 *
 * Depends:
 *	ui.core.js
 */
(function (a) { a.widget("ui.slider", a.extend({}, a.ui.mouse, { _init: function () { var b = this, c = this.options; this._keySliding = false; this._handleIndex = null; this._detectOrientation(); this._mouseInit(); this.element.addClass("ui-slider ui-slider-" + this.orientation + " ui-widget ui-widget-content ui-corner-all"); this.range = a([]); if (c.range) { if (c.range === true) { this.range = a("<div></div>"); if (!c.values) { c.values = [this._valueMin(), this._valueMin()] } if (c.values.length && c.values.length != 2) { c.values = [c.values[0], c.values[0]] } } else { this.range = a("<div></div>") } this.range.appendTo(this.element).addClass("ui-slider-range"); if (c.range == "min" || c.range == "max") { this.range.addClass("ui-slider-range-" + c.range) } this.range.addClass("ui-widget-header") } if (a(".ui-slider-handle", this.element).length == 0) { a('<a href="#"></a>').appendTo(this.element).addClass("ui-slider-handle") } if (c.values && c.values.length) { while (a(".ui-slider-handle", this.element).length < c.values.length) { a('<a href="#"></a>').appendTo(this.element).addClass("ui-slider-handle") } } this.handles = a(".ui-slider-handle", this.element).addClass("ui-state-default ui-corner-all"); this.handle = this.handles.eq(0); this.handles.add(this.range).filter("a").click(function (d) { d.preventDefault() }).hover(function () { a(this).addClass("ui-state-hover") }, function () { a(this).removeClass("ui-state-hover") }).focus(function () { a(".ui-slider .ui-state-focus").removeClass("ui-state-focus"); a(this).addClass("ui-state-focus") }).blur(function () { a(this).removeClass("ui-state-focus") }); this.handles.each(function (d) { a(this).data("index.ui-slider-handle", d) }); this.handles.keydown(function (i) { var f = true; var e = a(this).data("index.ui-slider-handle"); if (b.options.disabled) { return } switch (i.keyCode) { case a.ui.keyCode.HOME: case a.ui.keyCode.END: case a.ui.keyCode.UP: case a.ui.keyCode.RIGHT: case a.ui.keyCode.DOWN: case a.ui.keyCode.LEFT: f = false; if (!b._keySliding) { b._keySliding = true; a(this).addClass("ui-state-active"); b._start(i, e) } break } var g, d, h = b._step(); if (b.options.values && b.options.values.length) { g = d = b.values(e) } else { g = d = b.value() } switch (i.keyCode) { case a.ui.keyCode.HOME: d = b._valueMin(); break; case a.ui.keyCode.END: d = b._valueMax(); break; case a.ui.keyCode.UP: case a.ui.keyCode.RIGHT: if (g == b._valueMax()) { return } d = g + h; break; case a.ui.keyCode.DOWN: case a.ui.keyCode.LEFT: if (g == b._valueMin()) { return } d = g - h; break } b._slide(i, e, d); return f }).keyup(function (e) { var d = a(this).data("index.ui-slider-handle"); if (b._keySliding) { b._stop(e, d); b._change(e, d); b._keySliding = false; a(this).removeClass("ui-state-active") } }); this._refreshValue() }, destroy: function () { this.handles.remove(); this.range.remove(); this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all").removeData("slider").unbind(".slider"); this._mouseDestroy() }, _mouseCapture: function (d) { var e = this.options; if (e.disabled) { return false } this.elementSize = { width: this.element.outerWidth(), height: this.element.outerHeight() }; this.elementOffset = this.element.offset(); var h = { x: d.pageX, y: d.pageY }; var j = this._normValueFromMouse(h); var c = this._valueMax() - this._valueMin() + 1, f; var k = this, i; this.handles.each(function (l) { var m = Math.abs(j - k.values(l)); if (c > m) { c = m; f = a(this); i = l } }); if (e.range == true && this.values(1) == e.min) { f = a(this.handles[++i]) } this._start(d, i); k._handleIndex = i; f.addClass("ui-state-active").focus(); var g = f.offset(); var b = !a(d.target).parents().andSelf().is(".ui-slider-handle"); this._clickOffset = b ? { left: 0, top: 0} : { left: d.pageX - g.left - (f.width() / 2), top: d.pageY - g.top - (f.height() / 2) - (parseInt(f.css("borderTopWidth"), 10) || 0) - (parseInt(f.css("borderBottomWidth"), 10) || 0) + (parseInt(f.css("marginTop"), 10) || 0) }; j = this._normValueFromMouse(h); this._slide(d, i, j); return true }, _mouseStart: function (b) { return true }, _mouseDrag: function (d) { var b = { x: d.pageX, y: d.pageY }; var c = this._normValueFromMouse(b); this._slide(d, this._handleIndex, c); return false }, _mouseStop: function (b) { this.handles.removeClass("ui-state-active"); this._stop(b, this._handleIndex); this._change(b, this._handleIndex); this._handleIndex = null; this._clickOffset = null; return false }, _detectOrientation: function () { this.orientation = this.options.orientation == "vertical" ? "vertical" : "horizontal" }, _normValueFromMouse: function (d) { var c, h; if ("horizontal" == this.orientation) { c = this.elementSize.width; h = d.x - this.elementOffset.left - (this._clickOffset ? this._clickOffset.left : 0) } else { c = this.elementSize.height; h = d.y - this.elementOffset.top - (this._clickOffset ? this._clickOffset.top : 0) } var f = (h / c); if (f > 1) { f = 1 } if (f < 0) { f = 0 } if ("vertical" == this.orientation) { f = 1 - f } var e = this._valueMax() - this._valueMin(), i = f * e, b = i % this.options.step, g = this._valueMin() + i - b; if (b > (this.options.step / 2)) { g += this.options.step } return parseFloat(g.toFixed(5)) }, _start: function (d, c) { var b = { handle: this.handles[c], value: this.value() }; if (this.options.values && this.options.values.length) { b.value = this.values(c); b.values = this.values() } this._trigger("start", d, b) }, _slide: function (f, e, d) { var g = this.handles[e]; if (this.options.values && this.options.values.length) { var b = this.values(e ? 0 : 1); if ((e == 0 && d >= b) || (e == 1 && d <= b)) { d = b } if (d != this.values(e)) { var c = this.values(); c[e] = d; var h = this._trigger("slide", f, { handle: this.handles[e], value: d, values: c }); var b = this.values(e ? 0 : 1); if (h !== false) { this.values(e, d, (f.type == "mousedown" && this.options.animate), true) } } } else { if (d != this.value()) { var h = this._trigger("slide", f, { handle: this.handles[e], value: d }); if (h !== false) { this._setData("value", d, (f.type == "mousedown" && this.options.animate)) } } } }, _stop: function (d, c) { var b = { handle: this.handles[c], value: this.value() }; if (this.options.values && this.options.values.length) { b.value = this.values(c); b.values = this.values() } this._trigger("stop", d, b) }, _change: function (d, c) { var b = { handle: this.handles[c], value: this.value() }; if (this.options.values && this.options.values.length) { b.value = this.values(c); b.values = this.values() } this._trigger("change", d, b) }, value: function (b) { if (arguments.length) { this._setData("value", b); this._change(null, 0) } return this._value() }, values: function (b, e, c, d) { if (arguments.length > 1) { this.options.values[b] = e; this._refreshValue(c); if (!d) { this._change(null, b) } } if (arguments.length) { if (this.options.values && this.options.values.length) { return this._values(b) } else { return this.value() } } else { return this._values() } }, _setData: function (b, d, c) { a.widget.prototype._setData.apply(this, arguments); switch (b) { case "orientation": this._detectOrientation(); this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-" + this.orientation); this._refreshValue(c); break; case "value": this._refreshValue(c); break } }, _step: function () { var b = this.options.step; return b }, _value: function () { var b = this.options.value; if (b < this._valueMin()) { b = this._valueMin() } if (b > this._valueMax()) { b = this._valueMax() } return b }, _values: function (b) { if (arguments.length) { var c = this.options.values[b]; if (c < this._valueMin()) { c = this._valueMin() } if (c > this._valueMax()) { c = this._valueMax() } return c } else { return this.options.values } }, _valueMin: function () { var b = this.options.min; return b }, _valueMax: function () { var b = this.options.max; return b }, _refreshValue: function (c) { var f = this.options.range, d = this.options, l = this; if (this.options.values && this.options.values.length) { var i, h; this.handles.each(function (p, n) { var o = (l.values(p) - l._valueMin()) / (l._valueMax() - l._valueMin()) * 100; var m = {}; m[l.orientation == "horizontal" ? "left" : "bottom"] = o + "%"; a(this).stop(1, 1)[c ? "animate" : "css"](m, d.animate); if (l.options.range === true) { if (l.orientation == "horizontal") { (p == 0) && l.range.stop(1, 1)[c ? "animate" : "css"]({ left: o + "%" }, d.animate); (p == 1) && l.range[c ? "animate" : "css"]({ width: (o - lastValPercent) + "%" }, { queue: false, duration: d.animate }) } else { (p == 0) && l.range.stop(1, 1)[c ? "animate" : "css"]({ bottom: (o) + "%" }, d.animate); (p == 1) && l.range[c ? "animate" : "css"]({ height: (o - lastValPercent) + "%" }, { queue: false, duration: d.animate }) } } lastValPercent = o }) } else { var j = this.value(), g = this._valueMin(), k = this._valueMax(), e = k != g ? (j - g) / (k - g) * 100 : 0; var b = {}; b[l.orientation == "horizontal" ? "left" : "bottom"] = e + "%"; this.handle.stop(1, 1)[c ? "animate" : "css"](b, d.animate); (f == "min") && (this.orientation == "horizontal") && this.range.stop(1, 1)[c ? "animate" : "css"]({ width: e + "%" }, d.animate); (f == "max") && (this.orientation == "horizontal") && this.range[c ? "animate" : "css"]({ width: (100 - e) + "%" }, { queue: false, duration: d.animate }); (f == "min") && (this.orientation == "vertical") && this.range.stop(1, 1)[c ? "animate" : "css"]({ height: e + "%" }, d.animate); (f == "max") && (this.orientation == "vertical") && this.range[c ? "animate" : "css"]({ height: (100 - e) + "%" }, { queue: false, duration: d.animate }) } } })); a.extend(a.ui.slider, { getter: "value values", version: "1.7.1", eventPrefix: "slide", defaults: { animate: false, delay: 0, distance: 0, max: 100, min: 0, orientation: "horizontal", range: false, step: 1, value: 0, values: null} }) })(jQuery); ;


/**
* Copyright (c) 2005 - 2010, James Auldridge
* All rights reserved.
*
* Licensed under the BSD, MIT, and GPL (your choice!) Licenses:
*  http://code.google.com/p/cookies/wiki/License
*
*/
var jaaulde = window.jaaulde || {}; jaaulde.utils = jaaulde.utils || {}; jaaulde.utils.cookies = (function () {
    var resolveOptions, assembleOptionsString, parseCookies, constructor, defaultOptions = { expiresAt: null, path: '/', domain: null, secure: false }; resolveOptions = function (options) {
        var returnValue, expireDate; if (typeof options !== 'object' || options === null) { returnValue = defaultOptions; } else
        { returnValue = { expiresAt: defaultOptions.expiresAt, path: defaultOptions.path, domain: defaultOptions.domain, secure: defaultOptions.secure }; if (typeof options.expiresAt === 'object' && options.expiresAt instanceof Date) { returnValue.expiresAt = options.expiresAt; } else if (typeof options.hoursToLive === 'number' && options.hoursToLive !== 0) { expireDate = new Date(); expireDate.setTime(expireDate.getTime() + (options.hoursToLive * 60 * 60 * 1000)); returnValue.expiresAt = expireDate; } if (typeof options.path === 'string' && options.path !== '') { returnValue.path = options.path; } if (typeof options.domain === 'string' && options.domain !== '') { returnValue.domain = options.domain; } if (options.secure === true) { returnValue.secure = options.secure; } } return returnValue;
    }; assembleOptionsString = function (options) { options = resolveOptions(options); return ((typeof options.expiresAt === 'object' && options.expiresAt instanceof Date ? '; expires=' + options.expiresAt.toGMTString() : '') + '; path=' + options.path + (typeof options.domain === 'string' ? '; domain=' + options.domain : '') + (options.secure === true ? '; secure' : '')); }; parseCookies = function () {
        var cookies = {}, i, pair, name, value, separated = document.cookie.split(';'), unparsedValue; for (i = 0; i < separated.length; i = i + 1) {
            pair = separated[i].split('='); name = pair[0].replace(/^\s*/, '').replace(/\s*$/, ''); try
{ value = decodeURIComponent(pair[1]); } catch (e1) { value = pair[1]; } if (typeof JSON === 'object' && JSON !== null && typeof JSON.parse === 'function') {
                try
{ unparsedValue = value; value = JSON.parse(value); } catch (e2) { value = unparsedValue; } 
            } cookies[name] = value;
        } return cookies;
    }; constructor = function () { }; constructor.prototype.get = function (cookieName) {
        var returnValue, item, cookies = parseCookies(); if (typeof cookieName === 'string') { returnValue = (typeof cookies[cookieName] !== 'undefined') ? cookies[cookieName] : null; } else if (typeof cookieName === 'object' && cookieName !== null) {
            returnValue = {}; for (item in cookieName) {
                if (typeof cookies[cookieName[item]] !== 'undefined') { returnValue[cookieName[item]] = cookies[cookieName[item]]; } else
                { returnValue[cookieName[item]] = null; } 
            } 
        } else
        { returnValue = cookies; } return returnValue;
    }; constructor.prototype.filter = function (cookieNameRegExp) { var cookieName, returnValue = {}, cookies = parseCookies(); if (typeof cookieNameRegExp === 'string') { cookieNameRegExp = new RegExp(cookieNameRegExp); } for (cookieName in cookies) { if (cookieName.match(cookieNameRegExp)) { returnValue[cookieName] = cookies[cookieName]; } } return returnValue; }; constructor.prototype.set = function (cookieName, value, options) {
        if (typeof options !== 'object' || options === null) { options = {}; } if (typeof value === 'undefined' || value === null) { value = ''; options.hoursToLive = -8760; } else if (typeof value !== 'string') {
            if (typeof JSON === 'object' && JSON !== null && typeof JSON.stringify === 'function') { value = JSON.stringify(value); } else
            { throw new Error('cookies.set() received non-string value and could not serialize.'); } 
        } var optionsString = assembleOptionsString(options); document.cookie = cookieName + '=' + encodeURIComponent(value) + optionsString;
    }; constructor.prototype.del = function (cookieName, options) { var allCookies = {}, name; if (typeof options !== 'object' || options === null) { options = {}; } if (typeof cookieName === 'boolean' && cookieName === true) { allCookies = this.get(); } else if (typeof cookieName === 'string') { allCookies[cookieName] = true; } for (name in allCookies) { if (typeof name === 'string' && name !== '') { this.set(name, null, options); } } }; constructor.prototype.test = function () { var returnValue = false, testName = 'cT', testValue = 'data'; this.set(testName, testValue); if (this.get(testName) === testValue) { this.del(testName); returnValue = true; } return returnValue; }; constructor.prototype.setOptions = function (options) { if (typeof options !== 'object') { options = null; } defaultOptions = resolveOptions(options); }; return new constructor();
})(); (function () {
    if (window.jQuery) {
        (function ($) {
            $.cookies = jaaulde.utils.cookies; var extensions = { cookify: function (options) {
                return this.each(function () {
                    var i, nameAttrs = ['name', 'id'], name, $this = $(this), value; for (i in nameAttrs) {
                        if (!isNaN(i)) {
                            name = $this.attr(nameAttrs[i]); if (typeof name === 'string' && name !== '') {
                                if ($this.is(':checkbox, :radio')) { if ($this.attr('checked')) { value = $this.val(); } } else if ($this.is(':input')) { value = $this.val(); } else
                                { value = $this.html(); } if (typeof value !== 'string' || value === '') { value = null; } $.cookies.set(name, value, options); break;
                            } 
                        } 
                    } 
                });
            }, cookieFill: function () {
                return this.each(function () {
                    var n, getN, nameAttrs = ['name', 'id'], name, $this = $(this), value; getN = function () { n = nameAttrs.pop(); return !!n; }; while (getN()) {
                        name = $this.attr(n); if (typeof name === 'string' && name !== '') {
                            value = $.cookies.get(name); if (value !== null) {
                                if ($this.is(':checkbox, :radio')) {
                                    if ($this.val() === value) { $this.attr('checked', 'checked'); } else
                                    { $this.removeAttr('checked'); } 
                                } else if ($this.is(':input')) { $this.val(value); } else
                                { $this.html(value); } 
                            } break;
                        } 
                    } 
                });
            }, cookieBind: function (options) { return this.each(function () { var $this = $(this); $this.cookieFill().change(function () { $this.cookify(options); }); }); } 
            }; $.each(extensions, function (i) { $.fn[i] = this; });
        })(window.jQuery);
    }
})();

/*global jQuery */
/* ****************************************************************************

	CJ Object Scaler jQuery Plug-In v2.0

	This library is released under the BSD license:

	Copyright (c) 2008, Doug Jones. All rights reserved.
	
	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions are met:
	
	Redistributions of source code must retain the above copyright notice, this
	list of conditions and the following disclaimer. Redistributions in binary
	form must reproduce the above copyright notice, this list of conditions and
	the following disclaimer in the documentation and/or other materials
	provided with the distribution. Neither the name BernieCode nor
	the names of its contributors may be used to endorse or promote products
	derived from this software without specific prior written permission. 
	
	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
	AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
	IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
	ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
	ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
	DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
	SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
	CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
	LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
	OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
	DAMAGE.
	
	For more information please visit www.cjboco.com.
	
	Example:
	
	$("#myImage").cjObjectScaler({
		destObj: $("#myDiv"),	// Needs to be a jQuery object
		method: "fit",			// fit | fill (default)
		fade: 500				// 0 no fade, positive integer fade duration
	});
	
	CHANGELOG
	
		v1.0	09/10/08 -	Initial Release
		v2.0	09/22/09 -	Coverted it to a jQuery plug-in
		v2.0.1	10/14/09 -	Fixed a bug where the scaling function
								wasn't being triggered, do to the
								image already being loaded.
								(Discovered by Ben Visser)
	

**************************************************************************** */
(function ($) {
	$.fn.cjObjectScaler = function (options) {

		/* 
			user variables (settings)
		***************************************/
		var settings = {
			// user editable settings
			destObj: null,
			// must be a jQuery object
			method: "fill",
			// fit|fill
			fade: 0 // if positive value, do hide/fadeIn
		};

		/* 
			system variables
		***************************************/
		var sys = {
			// function parameters
			version: '2.0.0',
			elem: null
		};

		/* 
			scale the image
		***************************************/
		function scale(self) {

			// declare some local variables
			var dest = settings.destObj,
			destW = $(dest).width(),
			destH = $(dest).height(),
			ratioX,
			ratioY,
			scale,
			newWidth,
			newHeight;

			// calculate scale ratios
			ratioX = destW / $(self).width();
			ratioY = destH / $(self).height();

			// Determine which algorithm to use
			if (!$(self).hasClass("cf_image_scaler_fill") && ($(self).hasClass("cf_image_scaler_fit") || settings.method === "fit")) {
				scale = ratioX < ratioY ? ratioX : ratioY;
			} else if (!$(self).hasClass("cf_image_scaler_fit") && ($(self).hasClass("cf_image_scaler_fill") || settings.method === "fill")) {
				scale = ratioX > ratioY ? ratioX : ratioY;
			}

			// calculate our new image dimensions
			newWidth = parseInt($(self).width() * scale, 10);
			newHeight = parseInt($(self).height() * scale, 10);

			// Set new dimensions & offset
			$(self).css({
				"width": newWidth + "px",
				"height": newHeight + "px",
				"position": "absolute",
				"top": parseInt((destH - newHeight) / 2, 10) + "px",
				"left": parseInt((destW - newWidth) / 2, 10) + "px"
			}).attr({
				"width": newWidth,
				"height": newHeight
			});

			// do our fancy fade in, if user supplied a fade amount
			if (settings.fade > 0) {
				$(self).fadeIn(settings.fade);
			}

		}

		/* 
			initialize the flipBox
		***************************************/
		function init() {

			var self = $(sys.elem)[0];

			// check to make sure we have a valid destination object
			if (settings.destObj === null || typeof settings.method !== "string" || typeof $(settings.destObj)[0] !== "object") {
				return;
			} else {

				// need to make sure the user set the parent's position
				// things go bonkers, if not set.
				if ($(settings.destObj).css("position") === "static") {
					$(settings.destObj).css({
						"position": "relative"
					});
				}

				// if the user supplied a fade amount, hide our image
				if (settings.fade > 0) {
					$(self).hide();
				}

				// run our scale function. Special case for images, we need
				// to make sure the image has loaded in order to get the width & height
				if ($(self)[0].nodeName === "IMG") {
					// check to see if the image is already loaded
					if ($(self).attr("complete")) {
						scale($(self)[0]);
					} else {
						$(self).load(function () {
							scale($(self)[0]);
						});
					}
				} else {
					scale($(self)[0]);
				}

			}
		}

		/* 
			set up any user passed variables
		***************************************/
		if (options) {
			$.extend(settings, options);
		}

		/* 
			main
		***************************************/
		return this.each(function () {
			sys.elem = this;
			init();
		});

	};
})(jQuery);

/**
 * Flash (http://jquery.lukelutman.com/plugins/flash)
 * A jQuery plugin for embedding Flash movies.
 * 
 * Version 1.0
 * November 9th, 2006
 *
 * Copyright (c) 2006 Luke Lutman (http://www.lukelutman.com)
 * Dual licensed under the MIT and GPL licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.opensource.org/licenses/gpl-license.php
 * 
 * Inspired by:
 * SWFObject (http://blog.deconcept.com/swfobject/)
 * UFO (http://www.bobbyvandersluis.com/ufo/)
 * sIFR (http://www.mikeindustries.com/sifr/)
 * 
 * IMPORTANT: 
 * The packed version of jQuery breaks ActiveX control
 * activation in Internet Explorer. Use JSMin to minifiy
 * jQuery (see: http://jquery.lukelutman.com/plugins/flash#activex).
 *
 **/ 
;(function() {

    var $$;

    /**
    * 
    * @desc Replace matching elements with a flash movie.
    * @author Luke Lutman
    * @version 1.0.1
    *
    * @name flash
    * @param Hash htmlOptions Options for the embed/object tag.
    * @param Hash pluginOptions Options for detecting/updating the Flash plugin (optional).
    * @param Function replace Custom block called for each matched element if flash is installed (optional).
    * @param Function update Custom block called for each matched if flash isn't installed (optional).
    * @type jQuery
    *
    * @cat plugins/flash
    * 
    * @example $('#hello').flash({ src: 'hello.swf' });
    * @desc Embed a Flash movie.
    *
    * @example $('#hello').flash({ src: 'hello.swf' }, { version: 8 });
    * @desc Embed a Flash 8 movie.
    *
    * @example $('#hello').flash({ src: 'hello.swf' }, { expressInstall: true });
    * @desc Embed a Flash movie using Express Install if flash isn't installed.
    *
    * @example $('#hello').flash({ src: 'hello.swf' }, { update: false });
    * @desc Embed a Flash movie, don't show an update message if Flash isn't installed.
    *
    **/
    $$ = jQuery.fn.flash = function(htmlOptions, pluginOptions, replace, update) {

        // Set the default block.
        var block = replace || $$.replace;

        // Merge the default and passed plugin options.
        pluginOptions = $$.copy($$.pluginOptions, pluginOptions);

        // Detect Flash.
        if (!$$.hasFlash(pluginOptions.version)) {
            // Use Express Install (if specified and Flash plugin 6,0,65 or higher is installed).
            if (pluginOptions.expressInstall && $$.hasFlash(6, 0, 65)) {
                // Add the necessary flashvars (merged later).
                var expressInstallOptions = {
                    flashvars: {
                        MMredirectURL: location,
                        MMplayerType: 'PlugIn',
                        MMdoctitle: jQuery('title').text()
                    }
                };
                // Ask the user to update (if specified).
            } else if (pluginOptions.update) {
                // Change the block to insert the update message instead of the flash movie.
                block = update || $$.update;
                // Fail
            } else {
                // The required version of flash isn't installed.
                // Express Install is turned off, or flash 6,0,65 isn't installed.
                // Update is turned off.
                // Return without doing anything.
                return this;
            }
        }

        // Merge the default, express install and passed html options.
        htmlOptions = $$.copy($$.htmlOptions, expressInstallOptions, htmlOptions);

        // Invoke $block (with a copy of the merged html options) for each element.
        return this.each(function() {
            block.call(this, $$.copy(htmlOptions));
        });

    };
    /**
    *
    * @name flash.copy
    * @desc Copy an arbitrary number of objects into a new object.
    * @type Object
    * 
    * @example $$.copy({ foo: 1 }, { bar: 2 });
    * @result { foo: 1, bar: 2 };
    *
    **/
    $$.copy = function() {
        var options = {}, flashvars = {};
        for (var i = 0; i < arguments.length; i++) {
            var arg = arguments[i];
            if (arg == undefined) continue;
            jQuery.extend(options, arg);
            // don't clobber one flash vars object with another
            // merge them instead
            if (arg.flashvars == undefined) continue;
            jQuery.extend(flashvars, arg.flashvars);
        }
        options.flashvars = flashvars;
        return options;
    };
    /*
    * @name flash.hasFlash
    * @desc Check if a specific version of the Flash plugin is installed
    * @type Boolean
    *
    **/
    $$.hasFlash = function() {
        // look for a flag in the query string to bypass flash detection
        if (/hasFlash\=true/.test(location)) return true;
        if (/hasFlash\=false/.test(location)) return false;
        var pv = $$.hasFlash.playerVersion().match(/\d+/g);
        var rv = String([arguments[0], arguments[1], arguments[2]]).match(/\d+/g) || String($$.pluginOptions.version).match(/\d+/g);
        for (var i = 0; i < 3; i++) {
            pv[i] = parseInt(pv[i] || 0);
            rv[i] = parseInt(rv[i] || 0);
            // player is less than required
            if (pv[i] < rv[i]) return false;
            // player is greater than required
            if (pv[i] > rv[i]) return true;
        }
        // major version, minor version and revision match exactly
        return true;
    };
    /**
    *
    * @name flash.hasFlash.playerVersion
    * @desc Get the version of the installed Flash plugin.
    * @type String
    *
    **/
    $$.hasFlash.playerVersion = function() {
        // ie
        try {
            try {
                // avoid fp6 minor version lookup issues
                // see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
                var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
                try { axo.AllowScriptAccess = 'always'; }
                catch (e) { return '6,0,0'; }
            } catch (e) { }
            return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
            // other browsers
        } catch (e) {
            try {
                if (navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin) {
                    return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
                }
            } catch (e) { }
        }
        return '0,0,0';
    };
    /**
    *
    * @name flash.htmlOptions
    * @desc The default set of options for the object or embed tag.
    *
    **/
    $$.htmlOptions = {
        height: 240,
        flashvars: {},
        pluginspage: 'http://www.adobe.com/go/getflashplayer',
        src: '#',
        type: 'application/x-shockwave-flash',
        width: 320,
        _class: 'myFlash',
        _borderWidth:15
    };
    /**
    *
    * @name flash.pluginOptions
    * @desc The default set of options for checking/updating the flash Plugin.
    *
    **/
    $$.pluginOptions = {
        expressInstall: false,
        update: true,
        version: '6.0.65'
    };
    /**
    *
    * @name flash.replace
    * @desc The default method for replacing an element with a Flash movie.
    *
    **/
    $$.replace = function(htmlOptions) {
        this.innerHTML = '<div class="alt">' + this.innerHTML + '</div>';
        jQuery(this)
		.addClass('flash-replaced')
		.prepend($$.transform(htmlOptions));
    };
    /**
    *
    * @name flash.update
    * @desc The default method for replacing an element with an update message.
    *
    **/
    $$.update = function(htmlOptions) {
        var url = String(location).split('?');
        url.splice(1, 0, '?hasFlash=true&');
        url = url.join('');
        var msg = '<p>This content requires the Flash Player. <a href="http://www.adobe.com/go/getflashplayer">Download Flash Player</a>. Already have Flash Player? <a href="' + url + '">Click here.</a></p>';
        this.innerHTML = '<span class="alt">' + this.innerHTML + '</span>';
        jQuery(this)
		.addClass('flash-update')
		.prepend(msg);
    };
    /**
    *
    * @desc Convert a hash of html options to a string of attributes, using Function.apply(). 
    * @example toAttributeString.apply(htmlOptions)
    * @result foo="bar" foo="bar"
    *
    **/
    function toAttributeString() {
        var s = '';
        for (var key in this)
            if (typeof this[key] != 'function')
            s += key + '="' + this[key] + '" ';
        return s;
    };
    /**
    *
    * @desc Convert a hash of flashvars to a url-encoded string, using Function.apply(). 
    * @example toFlashvarsString.apply(flashvarsObject)
    * @result foo=bar&foo=bar
    *
    **/
    function toFlashvarsString() {
        var s = '';
        for (var key in this)
            if (typeof this[key] != 'function')
            s += key + '=' + encodeURIComponent(this[key]) + '&';
        return s.replace(/&$/, '');
    };
    /**
    *
    * @name flash.transform
    * @desc Transform a set of html options into an embed tag.
    * @type String 
    *
    * @example $$.transform(htmlOptions)
    * @result <embed src="foo.swf" ... />
    *
    * Note: The embed tag is NOT standards-compliant, but it 
    * works in all current browsers. flash.transform can be
    * overwritten with a custom function to generate more 
    * standards-compliant markup.
    *
    **/
    $$.transform = function(htmlOptions) {
        htmlOptions.toString = toAttributeString;
        var bannerWidth = htmlOptions.width - htmlOptions._borderWidth;
       
        if (htmlOptions.flashvars) htmlOptions.flashvars.toString = toFlashvarsString;
        return '<embed onclick="" id="' + htmlOptions._class + '" ' + String(htmlOptions) + ' wmode="transparent" class="' + htmlOptions._class + '" style="width:' + bannerWidth + 'px;" />';
    };

    /**
    *
    * Flash Player 9 Fix (http://blog.deconcept.com/2006/07/28/swfobject-143-released/)
    *
    **/
    if (window.attachEvent) {
        window.attachEvent("onbeforeunload", function() {
            __flash_unloadHandler = function() { };
            __flash_savedUnloadHandler = function() { };
        });
    }

})();
/* jScale Image Scaler v1.01
* Last updated: Aug 6th, 2009: Fixed bug when "ls (largest side)" option is used
* Author: JavaScript Kit at http://www.javascriptkit.com/
* Visit http://www.javascriptkit.com/script/script2/jScale/ for full source code
*/

jQuery.jScale = {
    getnewSize: function(side, nvalue) {
        var otherside = (side == "w") ? "h" : "w"
        if (typeof nvalue == "undefined" || nvalue == null) //if this side has no explicit size set, scale it
            var newSize = this.ndimensions[otherside] * this.odimensions[side] / this.odimensions[otherside]
        else
            var newSize = (/%/.test(nvalue)) ? parseInt(nvalue) / 100 * this.odimensions[side] : parseInt(nvalue)
        this.ndimensions[side] = Math.round(newSize)
    },
    getnewDimensions: function($, imgref, setting, callback) {
        //create temporary floating image to get original image's true dimensions (in case width/height attr set)
        var $tempimg = $('<img src="' + imgref.src + '" style="position:absolute; top:0; left:0; visibility:hidden" />').prependTo('body')
        this.odimensions = { w: $tempimg.width(), h: $tempimg.height()} //get image dimensions
        var sortbysize = (this.odimensions.w > this.odimensions.h) ? ["w", "h"] : ["h", "w"] //array to determine [largerside, shorterside]
        this.ndimensions = {}
        if (typeof setting.ls != "undefined") { //if setting.ls defined
            setting[sortbysize[0]] = setting.ls //set the correct side to the longest side's value setting
            setting[sortbysize[1]] = null
        }
        var sortbyavail = (setting.w) ? ["w", "h"] : (setting.h) ? ["h", "w"] : [] //check which side to work on based on availibility (which property is set by user)
        if (sortbyavail.length > 0) {
            this.getnewSize(sortbyavail[0], setting[sortbyavail[0]]) //work on side with property that's defined for sure first
            this.getnewSize(sortbyavail[1], setting[sortbyavail[1]]) //work on side with property that may or may not be defined last
            var callbackfunc = callback || function() { }
            if (setting.speed > 0)
                $(imgref).animate({ width: this.ndimensions.w + 'px', height: this.ndimensions.h + 'px' }, setting.speed, callbackfunc)
            else {
                $(imgref).css({ width: this.ndimensions.w + 'px', height: this.ndimensions.h + 'px' })
                callbackfunc.call(imgref)
            }
        }
        $tempimg.remove()
    }
};

jQuery.fn.jScale = function(setting, callback) {
    return this.each(function() { //return jQuery obj
        var imgref = this
        if (typeof setting == "undefined" || imgref.tagName != "IMG")
            return true //skip to next matched element
        if (imgref.complete) { //account for IE not firing image.onload
            jQuery.jScale.getnewDimensions(jQuery, imgref, setting, callback)
        }
        else {
            $(this).bind('load', function() {
                jQuery.jScale.getnewDimensions(jQuery, imgref, setting, callback)
            })
        }
    })
};


/*2nd PORTAL FUNCTIONS*/




$(document).ready(function() {

$('#dHeader ul, #dFooter ul').RemoveLastBorder();



$('.iwkContactForm .btnSend').StyleButton({ cssClass: 'styledButton' });
$('.iwkRecruitment a.btnSubmit').StyleButton({ cssClass: 'styledButton' });
$('.iwkAdvancedSearch a.btnSearch').StyleButton({ cssClass: 'styledButton' });
$('.iwkSimpleSearch a.btnSearch').StyleButton({ cssClass: 'styledButton' });
$('.iwkPropertyDetail .requestSendAction a').StyleButton({ cssClass: 'styledButton' });
$('.newsletter a').StyleButton({ cssClass: 'styledButton' });

if ($('.iwkPropertyDetail').length > 0) {

//Duplicate Property Owner's Info to side container
$('#ownerInfoContainer').append($('#tabOwner'));

//Duplicate Property Owner's Info to side container
if ($('#tabVideos').length > 0)
$('#videoContainer').append($('#tabVideos'));
else
$('#videoContainer').parent().hide();

}

setInterval("BannerSlideshow()", 5000);

});


jQuery.fn.delay = function (time, func) {
    this.each(function () {
        setTimeout(func, time);
    });

    return this;
};

// Global variables.
var iwkPropertyCarousel;
var iwkPCControlKeys;

function iwkPCKey(id) {
    var key = -1;
    try {
        var j;
        for (j = 0; j < iwkPCControlKeys.length; j++) {
            if (iwkPCControlKeys[j] == id) return j;
        }
        iwkPCControlKeys[j] = id;
        key = j;
    } catch (e) {
        iwkPCControlKeys = new Array();
        iwkPCControlKeys[0] = id;
        key = 0;
    }
    return key;
}

function iwkPropertyCarousel_Struct(ID, Loaded, EffectOn, ImagesLoading, Rows, Columns, Effect, EffectTime, ShowRedirect, TextPosition, TextAreaWidth) {
    this.ID = ID;
    this.Loaded = Loaded;
    this.EffectOn = EffectOn;
    this.ImagesLoading = ImagesLoading;
    this.Rows = Rows;
    this.Columns = Columns;
    this.Effect = Effect;
    this.EffectTime = EffectTime;
    this.ShowRedirect = ShowRedirect;
    this.TextPosition = TextPosition;
    this.TextAreaWidth = TextAreaWidth
    this.TotalItems = 0;
    this.ImageWidth = 0;
    this.ImageHeight = 0;
    this.ImagePathArray = new Array();
    this.AltTextArray = new Array();
    this.RedirectPathArray = new Array();
    this.TitleArray = new Array();
    this.ContentArray = new Array();
    this.PurposeArray = new Array();
    this.PriceArray = new Array();
    this.RedirectTextArray = new Array();
    this.CurrentSlide = 0;
    this.CurrentItem = 0;
    this.TotalWidth = 0;
    this.ImageLoadCount = 0;
    this.ImagesLoading = false;
    this.RowHeight = 0;
    this.RowWidth = 0;
}

// Load function
function InitPropertyCarousel(ControlID, rows, columns, effect, effectTime, showRedirect, TextPosition, TextAreaWidth) {
    try {
        iwkPropertyCarousel[iwkPCKey(ControlID)] = new iwkPropertyCarousel_Struct(ControlID, false, true, false, rows, columns, effect, effectTime, showRedirect, TextPosition, TextAreaWidth);
    } catch (e) {
        iwkPropertyCarousel = new Object();
        iwkPropertyCarousel[iwkPCKey(ControlID)] = new iwkPropertyCarousel_Struct(ControlID, false, true, false, rows, columns, effect, effectTime, showRedirect, TextPosition, TextAreaWidth);
    }

    var Control = iwkPropertyCarousel[iwkPCKey(ControlID)];


    try {

        Control.ImagePathArray[0] = "";
        Control.AltTextArray[0] = "";
        Control.RedirectPathArray[0] = "";
        Control.TitleArray[0] = "";
        Control.ContentArray[0] = "";
        Control.PurposeArray[0] = "";
        Control.PriceArray[0] = "";
        Control.RedirectTextArray[0] = "";

        $(document).ready(function () {

            $("#" + Control.ID).append("<div id='" + Control.ID + "_controlholder' class='CarouselHolder'></div>");
            $("#" + Control.ID + "_controlholder").hide();
            $("#" + Control.ID).append("<div id='" + Control.ID + "_controlLoader' class='CarouselLoader'><div class='CarouselLoadContent'><span class='CarouselLoadImage'>&nbsp;</span></div></div>");
            $("#" + Control.ID + "_controlLoader").hide();

            // loading values


            $("li").each(function () {
                if ($(this).parent().parent().attr("id") == Control.ID) {
                    Control.TotalItems = Control.TotalItems + 1;
                    Control.ImagePathArray[Control.TotalItems] = $(this).children("img").attr("src");
                    Control.AltTextArray[Control.TotalItems] = $(this).children("img").attr("alt");
                    if (Control.ImageWidth == 0) Control.ImageWidth = $(this).children("img").width();
                    if (Control.ImageHeight == 0) Control.ImageHeight = $(this).children("img").height();
                    Control.TitleArray[Control.TotalItems] = $(this).children("h4").text();
                    Control.RedirectPathArray[Control.TotalItems] = $(this).children("h4").children("a").attr("href");
                    Control.ContentArray[Control.TotalItems] = $(this).children("p:first").text();
                    Control.PurposeArray[Control.TotalItems] = $(this).children("p:last").text();
                    Control.PriceArray[Control.TotalItems] = $(this).children("cite").text();
                    Control.RedirectTextArray[Control.TotalItems] = $(this).children("a").text();
                    $(this).hide();
                }
            });

            Control.CurrentItem = Control.TotalItems;


            $("#" + Control.ID + "_controlLoader").height(Control.ImageHeight * Control.Rows);



            var itemNumber = 0;
            for (row = 1; row <= Control.Rows; row++) {

                $("#" + Control.ID + "_controlholder").append("<div id='" + Control.ID + "_row" + row + "' class='CarouselRow'></div>");
                for (column = 1; column <= Control.Columns; column++) {
                    if ((row * column) <= Control.TotalItems) {
                        itemNumber = itemNumber + 1;
                        iwkPropertyCarousel_AddItem(Control.ID + "_row" + row, itemNumber, Control);
                    }


                }
            }


            for (j = 1; j <= (Control.Rows * Control.Columns); j++) {
                if (j <= Control.TotalItems) {

                    $("#" + Control.ID + "_image" + j).load(function (event) {

                        Control.ImageLoadCount = Control.ImageLoadCount + 1;
                        if ((Control.ImageLoadCount == (Control.Rows * Control.Columns)) || (Control.ImageLoadCount == Control.TotalItems)) {

                            switch (Control.Effect) {
                                case "Shift":
                                    if (Control.Loaded != true) $("#" + Control.ID + "_controlLoader").fadeOut("slow", function () { $("#" + Control.ID + "_controlholder").fadeIn("slow"); });

                                    var prevItem = Control.CurrentItem - (Control.Rows * Control.Columns);
                                    if (prevItem <= 0) prevItem = Control.TotalItems + prevItem;
                                    if (Control.TotalItems < (Control.Rows * Control.Columns)) prevItem = 0;
                                    for (j = 1; j <= (Control.Rows * Control.Columns); j++) {
                                        if (j <= Control.TotalItems) {
                                            prevItem = prevItem + 1;
                                            if (prevItem > Control.TotalItems) prevItem = 1;

                                            iwkPropertyCarousel_SetDetails(j, prevItem, Control);

                                            if (Control.Loaded == true) {
                                                $("#" + Control.ID + "_imageBack" + j).fadeOut('slow', function () {

                                                    var index = iwkPropertyCarousel_GetIndexByID(Control.ID + "_imageBack", $(this).attr("id"), Control);

                                                    iwkPropertyCarousel_UpdateImage(Control.ID + "_imageBack" + index, $("#" + Control.ID + "_image" + index).attr("src"), $("#" + Control.ID + "_image" + index).attr("alt"));
                                                });
                                            } else {
                                                iwkPropertyCarousel_UpdateImage(Control.ID + "_imageBack" + j, $("#" + Control.ID + "_image" + j).attr("src"), $("#" + Control.ID + "_image" + j).attr("alt"));
                                                $("#" + Control.ID + "_controlItem" + j).fadeIn("slow");
                                            }
                                        }

                                    }
                                    break;

                            }
                            if (Control.Loaded != true) Control.Loaded = true;

                        }
                    });


                    $("#" + Control.ID + "_image" + j).click(function (event) {
                        var ImageIndex = iwkPropertyCarousel_GetIndexByID(Control.ID + "_image", event.target.id, Control);
                        var url = Control.RedirectPathArray[iwkPropertyCarousel_GetItemByIndex(ImageIndex, Control)];
                        if (url != "") window.location = url;
                    });

                    $("#" + Control.ID + "_image" + j).hover(function () {
                        Control.EffectOn = false;
                    }, function () {
                        Control.EffectOn = true;
                    });

                    $("#" + Control.ID + "_title" + j).hover(function () {
                        Control.EffectOn = false;
                    }, function () {
                        Control.EffectOn = true;
                    });

                    if (Control.ShowRedirect == true) {
                        $("#" + Control.ID + "_redirectbutton" + j).click(function (event) {
                            var ImageIndex = iwkPropertyCarousel_GetIndexByID(Control.ID + "_redirectbutton", event.target.id, Control);
                            var url = Control.RedirectPathArray[iwkPropertyCarousel_GetItemByIndex(ImageIndex, Control)];
                            if (url != "") window.location = url;
                        });
                        $("#" + Control.ID + "_redirectbutton" + j).hover(function () {
                            Control.EffectOn = false;
                        }, function () {
                            Control.EffectOn = true;
                        });
                    }
                }
            }



            for (j = 1; j <= Control.TotalItems; j++) {
                switch (Control.TextPosition) {
                    case "Bottom": case "Top":
                        $("#" + Control.ID + "_controlItem" + j).css("width", iwkPropertyCarousel_GetItemContentWidth("#" + Control.ID + "_controlItem1", Control.ImageWidth) + "px");
                        break;
                    case "RightSide": case "LeftSide":

                        $("#" + Control.ID + "_controlItem" + j).css("width", iwkPropertyCarousel_GetItemContentWidth("#" + Control.ID + "_controlItem1", Control.ImageWidth) + pixelsToInt(Control.TextAreaWidth) + "px");

                        break;
                }

            }

            iwkPropertyCarousel_RefreshTotalWidth(Control);

            $("#" + Control.ID + "_controlholder").css("width", Control.TotalWidth + "px");
            $("#" + Control.ID + "_controlLoader").css("width", Control.TotalWidth + "px");
            $("#" + Control.ID + "_controlLoader").fadeIn("slow");

            // Initialize Effect

            switch (Control.Effect) {
                case "Shift":
                    iwkPropertyCarousel_Shift(Control);
                    break;

                case "SlideLeft": case "SlideRight": case "Slide":

                    Control.CurrentSlide = "L";

                    Control.RowWidth = iwkPropertyCarousel_RefreshRowWidth(Control);
                    iwkPropertyCarousel_FindMaxRowHeight(Control);

                    $("#" + Control.ID + "_controlLoader").css("height", (Control.RowHeight * Control.Rows) + "px");
                    var itemNumber = 0;
                    Control.ImageLoadCount = 0;
                    for (row = 1; row <= Control.Rows; row++) {
                        $("#" + Control.ID + "_row" + row).css("overflow", "hidden");
                        $("#" + Control.ID + "_row" + row).css("position", "relative");
                        $("#" + Control.ID + "_row" + row).css("display", "block");
                        $("#" + Control.ID + "_row" + row).css("width", Control.TotalWidth + "px");
                        $("#" + Control.ID + "_row" + row).css("height", Control.RowHeight + "px");
                        $("#" + Control.ID + "_row" + row).append("<div id='" + Control.ID + "_inrow" + row + "F' ></div>");
                        $("#" + Control.ID + "_row" + row).append("<div id='" + Control.ID + "_inrow" + row + "L' ></div>");

                        $("#" + Control.ID + "_inrow" + row + "F").css("display", "table-cell");
                        $("#" + Control.ID + "_inrow" + row + "F").css("position", "absolute");
                        $("#" + Control.ID + "_inrow" + row + "F").css("top", "0px");
                        $("#" + Control.ID + "_inrow" + row + "F").css("left", "0px");

                        $("#" + Control.ID + "_inrow" + row + "L").css("display", "table-cell");
                        $("#" + Control.ID + "_inrow" + row + "L").css("position", "absolute");
                        $("#" + Control.ID + "_inrow" + row + "L").css("top", "0px");
                        var barnumbers = 2;
                        switch (Control.Effect) {
                            case "Slide":
                                $("#" + Control.ID + "_inrow" + row + "L").remove();
                                barnumbers = 1;
                                break;
                            case "SlideLeft":
                                $("#" + Control.ID + "_inrow" + row + "L").css("left", Control.RowWidth + "px");
                                $("#" + Control.ID + "_inrow" + row + "L").hide();
                                break;
                            case "SlideRight":
                                $("#" + Control.ID + "_inrow" + row + "L").css("left", "-" + Control.RowWidth + "px");
                                break;
                        }

                        var j;
                        for (i = 1; i <= Control.TotalItems; i++) {


                            if (i <= (Control.ID * Control.Columns)) $("#" + Control.ID + "_controlItem" + j).remove();
                            j = (row - 1) * Control.Columns + i
                            if (j > Control.TotalItems) j = j - Control.TotalItems;

                            for (k = 1; k <= barnumbers; k++) {
                                var bar
                                if (k == 1) bar = "F"; else bar = "L";

                                iwkPropertyCarousel_AddItem(Control.ID + "_inrow" + row + bar, row + bar + j, Control);
                                iwkPropertyCarousel_SetDetails(row + bar + j, j, Control);

                                $("#" + Control.ID + "_image" + row + bar + j).load(function (event) {
                                    Control.ImageLoadCount = Control.ImageLoadCount + 1;
                                    var barnumbers = 2;
                                    if (Control.Effect == "Slide") barnumbers = 1;
                                    if (Control.ImageLoadCount == (Control.TotalItems * rows * barnumbers)) {
                                        if (Control.Loaded != true) {

                                            $("#" + Control.ID + "_controlLoader").fadeOut("slow", function () { $("#" + Control.ID + "_controlholder").fadeIn("slow"); });

                                            for (r = 1; r <= Control.Rows; r++) {
                                                for (i = 1; i <= Control.TotalItems; i++) {
                                                    var IE7 = (navigator.appVersion.indexOf("MSIE 7.") == -1) ? false : true;
                                                    if (IE7 == false) {
                                                        $("#" + Control.ID + "_controlItem" + r + "F" + i).css("float", "none");
                                                        $("#" + Control.ID + "_controlItem" + r + "L" + i).css("float", "none");

                                                    } else {
                                                        $("#" + Control.ID + "_controlItem" + r + "F" + i).css("float", "left");
                                                        $("#" + Control.ID + "_controlItem" + r + "L" + i).css("float", "left");
                                                    }
                                                    $("#" + Control.ID + "_controlItem" + r + "F" + i).show();
                                                    setDisplay(Control.ID + "_controlItem" + r + "F" + i, "table-cell");
                                                    $("#" + Control.ID + "_controlItem" + r + "L" + i).show();
                                                    setDisplay(Control.ID + "_controlItem" + r + "L" + i, "table-cell");
                                                    switch (Control.TextPosition) {
                                                        case "RightSide": case "LeftSide":
                                                            $("#" + Control.ID + "_controlItem" + r + "F" + i).css("width", iwkPropertyCarousel_GetItemContentWidth("#" + Control.ID + "_controlItem" + r + "F" + i, Control.ImageWidth) + pixelsToInt(Control.TextAreaWidth) + "px");

                                                            $("#" + Control.ID + "_controlItem" + r + "L" + i).css("width", iwkPropertyCarousel_GetItemContentWidth("#" + Control.ID + "_controlItem" + r + "L" + i, Control.ImageWidth) + pixelsToInt(Control.TextAreaWidth) + "px");

                                                            break;

                                                    }
                                                }
                                            }
                                            Control.Loaded = true;
                                        }
                                    }
                                });


                                $("#" + Control.ID + "_image" + row + bar + j).click(function (event) {
                                    var ImageIndex = iwkPropertyCarousel_GetSlideIndexByID(Control.ID + "_image", event.target.id, Control);
                                    var url = Control.RedirectPathArray[ImageIndex];
                                    if (url != "") window.location = url;
                                });

                                $("#" + Control.ID + "_image" + row + bar + j).hover(function () {
                                    Control.EffectOn = false;
                                }, function () {
                                    Control.EffectOn = true;
                                });

                                $("#" + Control.ID + "_title" + row + bar + j).hover(function () {
                                    Control.EffectOn = false;
                                }, function () {
                                    Control.EffectOn = true;
                                });

                                if (Control.ShowRedirect == true) {
                                    $("#" + Control.ID + "_redirectbutton" + row + bar + j).click(function (event) {
                                        var ImageIndex = iwkPropertyCarousel_GetSlideIndexByID(Control.ID + "_redirectbutton", event.target.id, Control);
                                        var url = Control.RedirectPathArray[ImageIndex];
                                        if (url != "") window.location = url;
                                    });
                                    $("#" + Control.ID + "_redirectbutton" + row + bar + j).hover(function () {
                                        Control.EffectOn = false;
                                    }, function () {
                                        Control.EffectOn = true;
                                    });
                                }

                                iwkPropertyCarousel_UpdateImage(Control.ID + "_image" + row + bar + j, Control.ImagePathArray[j], Control.AltTextArray[j]);
                            }

                        }

                    }

                    switch (Control.Effect) {
                        case "Slide":
                            Control.CurrentSlide = "F";
                            iwkPropertyCarousel_Slide(0, -2, Control);
                            break;
                        case "SlideLeft":
                            iwkPropertyCarousel_Slide(-2, "L", Control);
                            break;
                        case "SlideRight":
                            iwkPropertyCarousel_Slide(+2, "", Control);
                            break;
                    }
                    break;


            }

        });
    }

    catch (e) {
        alert("Error in carousel control: Unable to load control \n\n" + e);
    }


}

function setDisplay(id, display) {
    $("#" + id).css("display", display);
}

function iwkPropertyCarousel_GetItemContentWidth(id, ImageWidth) {
    var itemWidth = 0;
    var counter = 0;
    $(id).children().each(function () {

        var obj = $(this);
        var objWidth = 0;
        var extraWidth;
        extraWidth = parseInt(obj.css("padding-left"), 10) + parseInt(obj.css("padding-right"), 10);
        if (isNaN(extraWidth) == false) objWidth += extraWidth;
        extraWidth = parseInt(obj.css("margin-left"), 10) + parseInt(obj.css("margin-right"), 10);
        if (isNaN(extraWidth) == false) objWidth += extraWidth;
        extraWidth = parseInt(obj.css("borderLeftWidth"), 10) + parseInt(obj.css("borderRightWidth"), 10);
        if (isNaN(extraWidth) == false) objWidth += extraWidth;
        if (objWidth > itemWidth) itemWidth = objWidth;
        counter += 1;
    });
    while (counter < $(id).children().length) { (1 == 1); }
    if (itemWidth == 0) {
        $(id).children("img").css("border", "2px solid transparent");
        itemWidth = 4;
    }
    itemWidth += ImageWidth;
    return itemWidth;
}

function iwkPropertyCarousel_GetSimpleElementContentWidth(id) {
    var itemWidth = 0;
    var counter = 0;
    $(id).children().each(function () {

        var obj = $(this);
        var objWidth = 0;
        var extraWidth;
        extraWidth = parseInt(obj.css("padding-left"), 10) + parseInt(obj.css("padding-right"), 10);
        if (isNaN(extraWidth) == false) objWidth += extraWidth;
        extraWidth = parseInt(obj.css("margin-left"), 10) + parseInt(obj.css("margin-right"), 10);
        if (isNaN(extraWidth) == false) objWidth += extraWidth;
        extraWidth = parseInt(obj.css("borderLeftWidth"), 10) + parseInt(obj.css("borderRightWidth"), 10);
        if (isNaN(extraWidth) == false) objWidth += extraWidth;
        objWidth += obj.width();
        if (objWidth > itemWidth) itemWidth = objWidth;
        counter += 1;
    });
    while (counter < $(id).children().length) { (1 == 1); }
    return itemWidth;
}

function iwkPropertyCarousel_GetItemWidth(id, ImageWidth) {
    var itemWidth = iwkPropertyCarousel_GetItemContentWidth(id, ImageWidth);

    var obj = $(".CarouselItem");
    var extraWidth;
    var addedWidth = 0;


    extraWidth = parseInt(obj.css("padding-left"), 10) + parseInt(obj.css("padding-right"), 10);
    if (isNaN(extraWidth) == false) addedWidth += extraWidth;
    extraWidth = parseInt(obj.css("margin-left"), 10) + parseInt(obj.css("margin-right"), 10);
    if (isNaN(extraWidth) == false) addedWidth += extraWidth;
    extraWidth = parseInt(obj.css("borderLeftWidth"), 10) + parseInt(obj.css("borderRightWidth"), 10);
    if (isNaN(extraWidth) == false) addedWidth += extraWidth;
    //        if (addedWidth == 0) {
    //            obj.css("border", "solid 5px transparent");
    //            addedWidth = 10;
    //        }
    itemWidth += addedWidth;
    return itemWidth;
}

function iwkPropertyCarousel_RefreshRowWidth(Control) {
    switch (Control.TextPosition) {
        case "Bottom": case "Top":
            Control.RowWidth = iwkPropertyCarousel_GetItemWidth("#" + Control.ID + "_controlItem1", Control.ImageWidth) * Control.TotalItems;
            break;
        case "RightSide": case "LeftSide":
            Control.RowWidth = (iwkPropertyCarousel_GetItemWidth("#" + Control.ID + "_controlItem1", Control.ImageWidth) + pixelsToInt(Control.TextAreaWidth)) * Control.TotalItems; ;
            break;
    }
    return Control.RowWidth;
}

function iwkPropertyCarousel_RefreshTotalWidth(Control) {


    switch (Control.TextPosition) {
        case "Bottom": case "Top":
            Control.TotalWidth = iwkPropertyCarousel_GetItemWidth("#" + Control.ID + "_controlItem1", Control.ImageWidth) * Control.Columns;
            break;
        case "RightSide": case "LeftSide":
            Control.TotalWidth = (iwkPropertyCarousel_GetItemWidth("#" + Control.ID + "_controlItem1", Control.ImageWidth) + pixelsToInt(Control.TextAreaWidth)) * Control.Columns; ;
            break;
    }
    return Control.TotalWidth;
}



function iwkPropertyCarousel_FindMaxRowHeight(Control) {
    $("#" + Control.ID).append("<div id='" + Control.ID + "_controlTemp' class='CarouselRow'>");
    Control.RowHeight = 0;
    for (j = 1; j <= Control.TotalItems; j++) {
        iwkPropertyCarousel_AddItem(Control.ID + "_controlTemp", j + "X", Control);
        iwkPropertyCarousel_SetDetails(j + "X", j, Control);
    }

    for (j = 1; j <= Control.TotalItems; j++) {
        if ($("#" + Control.ID + "_controlItem" + j + "X").height() > Control.RowHeight) Control.RowHeight = $("#" + Control.ID + "_controlItem" + j + "X").height();
    }

    var obj = $(".CarouselItem");
    var extraHeight;
    extraHeight = parseInt(obj.css("paddingTop"), 10) + parseInt(obj.css("paddingBottom"), 10);
    if (isNaN(extraHeight) == false) Control.RowHeight += extraHeight;
    extraHeight = parseInt(obj.css("marginTop"), 10) + parseInt(obj.css("marginBottom"), 10);
    if (isNaN(extraHeight) == false) Control.RowHeight += extraHeight;
    extraHeight = parseInt(obj.css("borderTopWidth"), 10) + parseInt(obj.css("borderTopWidth"), 10);
    if (isNaN(extraHeight) == false) Control.RowHeight += extraHeight;

    $("#" + Control.ID + "_controlTemp").remove();
}


function iwkPropertyCarousel_SetDetails(itemIndex, dataIndex, Control) {
    $("#" + Control.ID + "_title" + itemIndex).attr("href", Control.RedirectPathArray[dataIndex]);
    $("#" + Control.ID + "_title" + itemIndex).text(Control.TitleArray[dataIndex]);
    $("#" + Control.ID + "_content" + itemIndex).text(Control.ContentArray[dataIndex]);
    $("#" + Control.ID + "_purpose" + itemIndex).text(Control.PurposeArray[dataIndex]);
    $("#" + Control.ID + "_price" + itemIndex).text(Control.PriceArray[dataIndex]);
    if (Control.ShowRedirect == true) {
        $("#" + Control.ID + "_redirectbutton" + itemIndex).children("a").attr("href", Control.RedirectPathArray[dataIndex]);
        $("#" + Control.ID + "_redirectbutton" + itemIndex).children("a").children("span").text(Control.RedirectTextArray[dataIndex]);
    }
}

function iwkPropertyCarousel_AddItem(appendID, number, Control) {
    $("#" + appendID).append("<div id='" + Control.ID + "_controlItem" + number + "' class='CarouselItem'></div>");
    $("#" + Control.ID + "_controlItem" + number).hide();
    if (Control.Effect == "SheerLeft") { $("#" + Control.ID + "_controlItem" + number).css("padding", "0px"); }
    $("#" + Control.ID + "_controlItem" + number).append("<div id='" + Control.ID + "_imageHolder" + number + "' class='ImageHolder' ></div>");
    $("#" + Control.ID + "_imageHolder" + number).append("<img id='" + Control.ID + "_image" + number + "' class='CarouselImage' src='' />");
    reSize(Control.ID + "_image" + number, Control.ImageWidth, Control.ImageHeight);
    if (Control.Effect == "Shift") {
        $("#" + Control.ID + "_imageHolder" + number).append("<img id='" + Control.ID + "_imageBack" + number + "' class='CarouselImageBack' src='' />");
        reSize(Control.ID + "_imageBack" + number, Control.ImageWidth, Control.ImageHeight);
        $("#" + Control.ID + "_imageBack" + number).hide();
    }
    $("#" + Control.ID + "_controlItem" + number).append("<div id='" + Control.ID + "_textArea" + number + "' class='TextArea' ></div>");
    switch (Control.TextPosition) {
        case "LeftSide": case "Top":
            $("#" + Control.ID + "_textArea" + number).remove();
            $("#" + Control.ID + "_controlItem" + number).prepend("<div id='" + Control.ID + "_textArea" + number + "' class='TextArea' ></div>");
            if (Control.TextPosition == "Top") {
                $("#" + Control.ID + "_imageBack" + number).css("bottom", "0px");
                $("#" + Control.ID + "_imageBack" + number).css("left", "0px");
            }
            else {
                $("#" + Control.ID + "_imageBack" + number).css("right", "0px");
                $("#" + Control.ID + "_imageBack" + number).css("top", "0px");
            }

            break;
        case "Bottom": case "RightSide":
            $("#" + Control.ID + "_imageBack" + number).css("left", "0px");
            $("#" + Control.ID + "_imageBack" + number).css("top", "0px");
            break;
    }


    $("#" + Control.ID + "_textArea" + number).append("<h4><a id='" + Control.ID + "_title" + number + "' class='CarouselTitleLink' ></a></h4>");
    $("#" + Control.ID + "_textArea" + number).append("<div id='" + Control.ID + "_content" + number + "' class='CarouselContent' ></div>");
    $("#" + Control.ID + "_content" + number).width(Control.ImageWidth);
    $("#" + Control.ID + "_textArea" + number).append("<div id='" + Control.ID + "_purpose" + number + "' class='CarouselPurpose' ></div>");
    $("#" + Control.ID + "_textArea" + number).append("<div id='" + Control.ID + "_price" + number + "' class='CarouselPrice' ></div>");

    if (Control.ShowRedirect == true) {
        $("#" + Control.ID + "_textArea" + number).append("<div id='" + Control.ID + "_redirectbutton" + number + "' class='RedirectButton' ></div>");
        $("#" + Control.ID + "_redirectbutton" + number).append("<a><span></span></a>");
    }

    switch (Control.TextPosition) {
        case "Bottom": case "Top":
            $("#" + Control.ID + "_textArea" + number).css("width", "auto");
            break;
        case "RightSide": case "LeftSide":
            $("#" + Control.ID + "_textArea" + number).css("width", Control.TextAreaWidth);
            $("#" + Control.ID + "_textArea" + number).css("float", "left");
            $("#" + Control.ID + "_textArea" + number).children().css("padding-left", "10px");
            $("#" + Control.ID + "_imageHolder" + number).css("float", "left");
            break;
    }

}

function iwkPropertyCarousel_GetItemByIndex(index, Control) {
    if (Control.TotalItems <= (Control.Rows * Control.Columns)) {
        return index;
    } else {
        var Item = Control.CurrentItem - (Control.Rows * Control.Columns);
        if (Item <= 0) Item = Control.TotalItems + Item;
        Item = Item + index;
        if (Item > Control.TotalItems) Item = Item - Control.TotalItems;
        return Item;
    }
}

function iwkPropertyCarousel_ImageChange(number, itemNumber, Control) {

    if (Control.Loaded == true) $("#" + Control.ID + "_imageBack" + number).show();

    iwkPropertyCarousel_UpdateImage("" + Control.ID + "_image" + number, Control.ImagePathArray[itemNumber], Control.AltTextArray[itemNumber]);

}

function iwkPropertyCarousel_UpdateImage(imgID, imageUrl, imageAlt) {
    $("#" + imgID).attr("src", imageUrl);
    $("#" + imgID).attr("alt", imageAlt);
}

function iwkPropertyCarousel_GetIndexByID(lowID, id, Control) {
    var res = 0;
    for (var j = 1; j <= (Control.Rows * Control.Columns); j++) {
        if (j <= Control.TotalItems) {
            if (id == lowID + j) res = j;
        }
    }
    return res;
}


function iwkPropertyCarousel_GetSlideIndexByID(lowID, id, Control) {
    var res = 0;
    for (r = 1; r <= Control.Rows; r++) {
        for (var j = 1; j <= Control.TotalItems; j++) {
            if ((id == lowID + r + "F" + j) || (id == lowID + r + "L" + j)) res = j;
        }
    }
    return res;
}

function reSize(id, width, height) {
    $("#" + id).width(width);
    $("#" + id).height(height);
}

function pixelsToInt(pixels) {
    var result = pixels.substr(0, pixels.length - 2);
    return parseInt(result);
}

// EFFECTS

function iwkPropertyCarousel_Shift(Control) {
    Control.ImageLoadCount = 0;
    if (Control.EffectOn == true) {
        for (j = 1; j <= (Control.Rows * Control.Columns); j++) {
            if (j <= Control.TotalItems) {
                Control.CurrentItem = Control.CurrentItem + 1;
                if (Control.CurrentItem > Control.TotalItems) Control.CurrentItem = 1
                iwkPropertyCarousel_ImageChange(j, Control.CurrentItem, Control);
            }
        }
    }
    if ((Control.Rows * Control.Columns) < Control.TotalItems) $(this).delay(Control.EffectTime, function () { iwkPropertyCarousel_Shift(Control); });
}

function iwkPropertyCarousel_Slide(side, locked, Control) {
    if (Control.EffectOn == true) {
        var slideLeft = iwkPropertyCarousel_GetCssLeft(Control.ID + "_inrow1" + Control.CurrentSlide);
        var reset = false;
        var move = side;
        switch (true) {
            case (side < 0):
                if ((slideLeft + move) <= 0) reset = true;
                break;
            case (side > 0):
                if ((slideLeft + move) >= 0) reset = true;
                break;
            case (side == 0):
                move = locked;
                if ((slideLeft + move) >= 0) {
                    locked = -2;
                }
                if ((slideLeft + move) <= ((Control.RowWidth - Control.TotalWidth) * -1)) {
                    locked = 2;
                }
                break;
        }

        if (reset == true) {
            var mul;
            if (side < 0) mul = ""; else mul = "-";
            switch (Control.CurrentSlide) {
                case "F":
                    for (j = 1; j <= Control.Rows; j++) {
                        $("#" + Control.ID + "_inrow" + j + "F").css("left", "0px");
                        $("#" + Control.ID + "_inrow" + j + "L").css("left", mul + Control.RowWidth + "px");
                        if (side < 0) {
                            $("#" + Control.ID + "_inrow" + j + "L").hide();
                            locked = "L";
                        }
                        if (side > 0) {
                            $("#" + Control.ID + "_inrow" + j + "L").show();
                            locked = "";
                        }
                    }
                    Control.CurrentSlide = "L";
                    break;
                case "L":
                    for (j = 1; j <= Control.Rows; j++) {
                        $("#" + Control.ID + "_inrow" + j + "L").css("left", "0px");
                        $("#" + Control.ID + "_inrow" + j + "F").css("left", mul + Control.RowWidth + "px");
                        if (side < 0) {
                            $("#" + Control.ID + "_inrow" + j + "F").hide();
                            locked = "F";
                        }
                        if (side > 0) {
                            $("#" + Control.ID + "_inrow" + j + "F").show();
                            locked = "";
                        }
                    }
                    Control.CurrentSlide = "F";
                    break;
            }

        } else {
            var Fleft;
            var Lleft;
            for (j = 1; j <= Control.Rows; j++) {
                Fleft = iwkPropertyCarousel_GetCssLeft(Control.ID + "_inrow" + j + "F");
                if (side != 0) {
                    Lleft = iwkPropertyCarousel_GetCssLeft(Control.ID + "_inrow" + j + "L");
                    switch (true) {
                        case (side < 0):
                            if ((Lleft * -1) == (Control.RowWidth - Control.TotalWidth)) {
                                Fleft = Control.TotalWidth;
                                $("#" + Control.ID + "_inrow" + j + "F").show();
                                $("#" + Control.ID + "_inrow" + j + "F").children("div").each(function () {
                                    $(this).css("display", "table-cell");
                                });
                                locked = "";
                            }
                            if ((Fleft * -1) == (Control.RowWidth - Control.TotalWidth)) {
                                Lleft = Control.TotalWidth;
                                $("#" + Control.ID + "_inrow" + j + "L").show();
                                $("#" + Control.ID + "_inrow" + j + "L").children("div").each(function () {
                                    $(this).css("display", "table-cell");
                                });
                                locked = "";
                            }
                            break;
                        case (side > 0):
                            if ((Lleft * -1) == (Control.RowWidth - Control.TotalWidth)) {
                                $("#" + Control.ID + "_inrow" + j + "F").hide();
                                locked = "F";
                            }
                            if ((Fleft * -1) == (Control.RowWidth - Control.TotalWidth)) {
                                $("#" + Control.ID + "_inrow" + j + "L").hide();
                                locked = "L";
                            }
                            break;
                        case (side == 0):

                            break;
                    }

                    if (locked != "L") $("#" + Control.ID + "_inrow" + j + "L").css("left", (Lleft + move) + "px");
                }
                if (locked != "F") $("#" + Control.ID + "_inrow" + j + "F").css("left", (Fleft + move) + "px");
            }
        }
    }
    if ((Control.Rows * Control.Columns) < Control.TotalItems) {
        $(this).delay(Control.EffectTime, function () { iwkPropertyCarousel_Slide(side, locked, Control); });
    }

}

function iwkPropertyCarousel_GetCssLeft(id) {
    return pixelsToInt($("#" + id).css("left"));
}

function SetupAgencies(clientID) {
    $(document).ready(function() {
        var rbAgency = "#" + clientID + "_rbAgency";
        var rbDistrict = "#" + clientID + "_rbDistrict";
        var ddlAgencies = "#" + clientID + "_ddlAgencies";
        var ddlDistrict = "#" + clientID + "_ddlDistrict";
        var btnSearch = "#" + clientID + "_btnSearch";
        $(ddlDistrict).hide();

        $(rbAgency).click(function() {
            $(ddlDistrict).hide();
            $(ddlAgencies).show();
        });

        $(rbDistrict).click(function() {
            $(ddlAgencies).hide();
            $(ddlDistrict).show();
        });
        $(btnSearch).click(function() {
            if ($(rbAgency).is(':checked') == true && $(ddlAgencies).val() == 0)
                return false;
            if ($(rbDistrict).is(':checked') == true && $(ddlDistrict).val() == 0)
                return false;
        });
    });
}
    


/*	@ Remove last navigation's borders plugin
======================================================================================== */

function BannerSlideshow() {

    var $active = $("#dBanner img.active");

    if ($active.length == 0)
        $active = $("#dBanner img:last");

    var $next = $active.next().length ? $active.next() : $("#dBanner img:first");

    $active.addClass("last-active");

    $next.css({ opacity: 0.0 })
    	.addClass("active")
    	.animate({ opacity: 1.0 }, 1000, function() {
    	    $active.removeClass("active last-active");
    	});

  
}



/*	@ Remove last navigation's borders plugin
	======================================================================================== */
$.fn.RemoveLastBorder = function(options){
	return this.each(function(){
		$(this).children('li').filter(':last').css('border','none');
	});
};


/*	@ Style Buttons
	======================================================================================== */
$.fn.StyleButton = function(options) {
	var defaults = { cssClass:'' }
	var options = $.extend(defaults, options);
	return this.each(function(){
		var buttonText = $(this).text();
		$(this).addClass(options.cssClass).html('<span>' + buttonText + '</span>');
	});	
};


/* @ BANNERS - VIEW
================================================================================================================================== */
function LoadBanner(bannerPath, divClass, link, numberOfClicks, bannerID, url, isFlash,maskClass) {
    $(document).ready(function() {

        var content = $("." + divClass).parent();
           
        if (link != '#') {
            $('.' + divClass).css("cursor", "pointer");
        }

        LoadBannerPreview(bannerPath, $(content).width(), divClass, isFlash, maskClass, link, numberOfClicks, bannerID, url, $(content).height());
        $('.' + divClass).css("text-align", "center");

    });
}
    
    /* @ BANNERS - PREVIEW
================================================================================================================================== */
function LoadBannerPreview(bannerPath, bannerWidth, divClass, isFlash, maskClass,link,numberOfClicks,bannerID,url,bannerHeight) {
    $(window).load(function() {
        try {
            var borderWidth = 15;
            $('.' + divClass).css("visibility", "hidden");
            if (isFlash == '1') { //If is flash
                $('.' + divClass).flash({
                    src: bannerPath,
                    height: bannerHeight,
                    width: bannerWidth,
                    _class: "flash_" + divClass,
                    _borderWidth: borderWidth
                });

            }
            else { //if image

                $('.' + divClass).append("<img class='img_" + divClass + "' src='" + bannerPath + "' alt='banner'  />");
            }

            $('.' + divClass).jScale({ w: bannerWidth + 'px' });
            $('.' + maskClass).jScale({ w: bannerWidth + 'px' });

            $('.' + maskClass).click(function() {

                if (link != '#') {
                    numberOfClicks += 1;
                    //update number of clicks
                    UpdateNumberOfClicks(numberOfClicks, bannerID, url);
                    //Redirect to the link of the banner , if is valid
                    window.open(link);
                }
            });

            //Delay to mask configuration
            $(this).delay(3000, function() {
                //mask to click in banner link
                $('.' + maskClass).css("text-align", "center");
                $('.' + maskClass).css("width", bannerWidth);
                $('.' + maskClass).css("height", $('.' + divClass).css("width"));
                $('.' + divClass).css("z-index", "2");
                $('.' + maskClass).css("z-index", "3");
                if ($.browser.msie) {//If IE
                    $('.' + maskClass).css("background-color", "white");
                    $('.' + maskClass).css("filter", "alpha(opacity=1)");
                }

                $('.' + divClass).css("visibility", "visible");
            });

            //Delay to image configuration
            $(this).delay(2000, function() {
                if ($('.img_' + divClass).width != "null") {
                    if ($('.img_' + divClass).width() > bannerWidth) {
                        $('.img_' + divClass).jScale({ w: bannerWidth - borderWidth + 'px' });
                    }
                }
            });

        }
        catch (ex) {
        }
    });
}

   
//update the banner's number of clicks when a banner is clicked
function UpdateNumberOfClicks(numberOfClicks, bannerID, url) {
    $.getJSON(url + "?cid=" + bannerID + "&clicks=" + numberOfClicks);
}





function SetupBrokers(clientID) {
    $(document).ready(function () {

        var txtBrokersSearch = "#" + clientID + "_txtBrokersSearch";
        var btnSearch = "#" + clientID + "_btnSearch";

        $(btnSearch).click(function () {
            if ($(txtBrokersSearch).val() == "" || $(txtBrokersSearch).val() == null)
                return false;
        });
    });
}





function SetupSimpleSearch(propertyListURL, advancedSearchURL, handlersPath, clientID, loadingFeedback, mandatoryFieldsFeedback, emptyDistrict, emptyCounty, emptyParish, emptyZone,
                             qsPurpose, qsGroup, qsCountry, qsDistrict, qsCounty, qsParish, qsZone,
                             qsCondition, qsReference, qsMinTypo, qsMaxTypo,
                             qsMinPrice, qsMaxPrice, qsMinArea, qsMaxArea, isTypologySlider, isAreaSlider, isPriceSlider, valuesSeparator, showOnlyWithProperties) {
    $(document).ready(function () {

        //Fields declaration
        var ddlCountry = "#" + clientID + "_ddlCountry";
        var ddlDistrict = "#" + clientID + "_ddlDistrict";
        var ddlCounty = "#" + clientID + "_ddlCounty";
        var ddlParish = "#" + clientID + "_ddlParish";
        var ddlZone = "#" + clientID + "_ddlZone";
        var ddlPurpose = "#" + clientID + "_ddlPurpose";
        var ddlGroup = "#" + clientID + "_ddlGroup";
        var ddlCondition = "#" + clientID + "_ddlCondition";
        var ddlTypologyMin = "#" + clientID + "_ddlTypologyMin";
        var ddlTypologyMax = "#" + clientID + "_ddlTypologyMax";
        var ddlMinPrice = "#" + clientID + "_ddlMinPrice";
        var ddlMaxPrice = "#" + clientID + "_ddlMaxPrice";
        var ddlMinArea = "#" + clientID + "_ddlMinArea";
        var ddlMaxArea = "#" + clientID + "_ddlMaxArea";
        var lnkAdvancedSearch = "#" + clientID + "_lnkAdvancedSearch";
        var txtReference = "#" + clientID + "_txtReference";

        var btnSearch = "#" + clientID + "_btnSearch";


        //Events
        if (($(ddlCountry).val() != undefined) && ($(ddlCountry).val() > 0)) {
            BindDistricts();
        }

        if (($(ddlDistrict).val() != undefined) && ($(ddlDistrict).val() > 0)) {
            BindCounties();
        }

        if (($(ddlCounty).val() != undefined) && ($(ddlCounty).val() > 0)) {
            BindParishes($(ddlCounty).val());
        }

        //SelectIndexChange - ddlCountry
        $(ddlCountry).change(function () {
            BindDistricts();
        });

        //SelectIndexChange - ddlDistrict
        $(ddlDistrict).change(function () {
            BindCounties();
        });

        //SelectIndexChange - ddlCounty
        $(ddlCounty).change(function () {
            //GET  ID of County
            var idCounty = $(this).val();
            BindParishes(idCounty);
        });

        //SelectIndexChange - ddlParish
        $(ddlParish).change(function () {
            BindZones();
        });

        //SelectIndexChange - ddlParish
        $(ddlGroup).change(function () {

            BindAreas($(this).val());

        });

        //SelectIndexChange - ddlParish
        $(ddlPurpose).change(function () {
            BindPrices($(this).val());
        });


        //Bind the areas
        BindAreas($(ddlGroup).val());
        //Bind the prices
        BindPrices($(ddlPurpose).val());
        //Bind Typologies
        if (isTypologySlider == "true") {
            BindTypologies();
        };

        //On Click  - btnSearch
        $(btnSearch).click(function () {

            //field values declaration
            var purpose = $(ddlPurpose).val();
            var district = $(ddlDistrict).val();
            var country = $(ddlCountry).val();
            var county = $(ddlCounty).val();
            var zone = $(ddlZone).val();
            var parish = $(ddlParish).val();
            var typologyMin = $(ddlTypologyMin).val();
            var typologyMax = $(ddlTypologyMax).val();
            var priceMin = $(ddlMinPrice).val();
            var priceMax = $(ddlMaxPrice).val();
            var areaMin = $(ddlMinArea).val();
            var areaMax = $(ddlMaxArea).val();
            var condition = $(ddlCondition).val();
            var group = $(ddlGroup).val();

            var reference = $(txtReference).val();

            //if not portugal, district, county, parish are not mandatory
            if (country != 1 && country != undefined) {
                $(ddlDistrict).removeClass(clientID + "_mandatory");
                $(ddlCounty).removeClass(clientID + "_mandatory");
                $(ddlParish).removeClass(clientID + "_mandatory");
                $(ddlZone).removeClass(clientID + "_mandatory");
            }

            //get all objects mandatory
            var mandatoryFields = $("." + clientID + "_mandatory");
            var qString = "";
            var validSubmit = false;
            if (reference != "") {
                validSubmit = true;
            } else {
                validSubmit = isSubmitValid(mandatoryFields);
            }
            if (validSubmit == true) {
                //build query string with field values
                if (reference != "" && reference != undefined) {
                    qString = BuildQueryStringItem(qString, qsReference, reference);
                } else {
                    if (purpose > 0) qString = BuildQueryStringItem(qString, qsPurpose, purpose)
                    if (group > 0) qString = BuildQueryStringItem(qString, qsGroup, group)
                    if (condition > 0) qString = BuildQueryStringItem(qString, qsCondition, condition)
                    if (district > 0) qString = BuildQueryStringItem(qString, qsDistrict, district)
                    if (country > 0) qString = BuildQueryStringItem(qString, qsCountry, country)
                    if (county > 0) qString = BuildQueryStringItem(qString, qsCounty, county)
                    if (parish > 0) qString = BuildQueryStringItem(qString, qsParish, parish)
                    if (zone > 0) qString = BuildQueryStringItem(qString, qsZone, zone)
                    if (typologyMin > 0) qString = BuildQueryStringItem(qString, qsMinTypo, typologyMin)
                    if (typologyMax > 0) qString = BuildQueryStringItem(qString, qsMaxTypo, typologyMax)
                    if (priceMax > 0) qString = BuildQueryStringItem(qString, qsMaxPrice, priceMax)
                    if (priceMin > 0) qString = BuildQueryStringItem(qString, qsMinPrice, priceMin)
                    if (areaMin > 0) qString = BuildQueryStringItem(qString, qsMinArea, areaMin)
                    if (areaMax > 0) qString = BuildQueryStringItem(qString, qsMaxArea, areaMax)
                }
                var url = propertyListURL + qString;
                SendSearchToStats(qString);
                parent.location = url;

            }
            else {
                alert(mandatoryFieldsFeedback);
            }

            return false;
        });

        $(lnkAdvancedSearch).click(function () {

            //field values declaration
            var purpose = $(ddlPurpose).val();
            var district = $(ddlDistrict).val();
            var country = $(ddlCountry).val();
            var county = $(ddlCounty).val();
            var zone = $(ddlZone).val();
            var parish = $(ddlParish).val();
            var typologyMin = $(ddlTypologyMin).val();
            var typologyMax = $(ddlTypologyMax).val();
            var priceMin = $(ddlMinPrice).val();
            var priceMax = $(ddlMaxPrice).val();
            var areaMin = $(ddlMinArea).val();
            var areaMax = $(ddlMaxArea).val();
            var condition = $(ddlCondition).val();
            var group = $(ddlGroup).val();
            var reference = $(txtReference).val();


            var qString = "";
            //build query string with field values
            if (reference != "") qString = BuildQueryStringItem(qString, qsReference, reference)
            if (purpose > 0) qString = BuildQueryStringItem(qString, qsPurpose, purpose)
            if (group > 0) qString = BuildQueryStringItem(qString, qsGroup, group)
            if (condition > 0) qString = BuildQueryStringItem(qString, qsCondition, condition)
            if (district > 0) qString = BuildQueryStringItem(qString, qsDistrict, district)
            if (country > 0) qString = BuildQueryStringItem(qString, qsCountry, country)
            if (county > 0) qString = BuildQueryStringItem(qString, qsCounty, county)
            if (parish > 0) qString = BuildQueryStringItem(qString, qsParish, parish)
            if (zone > 0) qString = BuildQueryStringItem(qString, qsZone, zone)
            if (typologyMin > 0) qString = BuildQueryStringItem(qString, qsMinTypo, typologyMin)
            if (typologyMax > 0) qString = BuildQueryStringItem(qString, qsMaxTypo, typologyMax)
            if (priceMax > 0) qString = BuildQueryStringItem(qString, qsMaxPrice, priceMax)
            if (priceMin > 0) qString = BuildQueryStringItem(qString, qsMinPrice, priceMin)
            if (areaMin > 0) qString = BuildQueryStringItem(qString, qsMinArea, areaMin)
            if (areaMax > 0) qString = BuildQueryStringItem(qString, qsMaxArea, areaMax)

            var url = advancedSearchURL + qString;
            parent.location = url;

            return false;
        });


        //Get Districts
        function BindDistricts() {

            //RESET ddlDistrict
            $(ddlDistrict).html("");
            $(ddlDistrict).attr("disabled", "disabled");

            //RESET ddlCounties
            $(ddlCounty).html("");
            $(ddlCounty).attr("disabled", "disabled");

            //RESET ddlParish
            $(ddlParish).html("");
            $(ddlParish).attr("disabled", "disabled");

            //RESET ddlZone
            $(ddlZone).html("");
            $(ddlZone).attr("disabled", "disabled");

            //GET ID from ddlCountry
            var idCountry = $(ddlCountry).val();

            //IF SELECTED District
            if (idCountry != 0) {

                //GET Districts via JSON
                $(ddlDistrict).append($("<option></option>").val(0).html(loadingFeedback));

                $.getJSON(handlersPath + "/GetDistricts.ashx?cid=" + idCountry + "&withprop=" + showOnlyWithProperties.toString, function (Districts) {

                    if (Districts != null && Districts != "-1") {
                        $(ddlDistrict).html("");

                        //APPEND Districts on ddlDistricts
                        var hasRecords = false;

                        if (emptyDistrict != "") $(ddlDistrict).append($("<option></option>").val(0).html(emptyDistrict))
                        else $(ddlDistrict).append($("<option></option>").val(0).html(""))

                        $.each(Districts, function () {
                            $(ddlDistrict).append($("<option></option>").val(this['VALUE']).html(this['TEXT']));
                            hasRecords = true;
                        });
                        //ENABLE ddlDistricts
                        if (hasRecords) {
                            $(ddlDistrict).removeAttr("disabled");
                        }

                        ParseQueryString(qsDistrict, ddlDistrict);

                    }
                    else {
                        $(ddlDistrict).html("");
                    }
                });
            }
        }

        //GetCounties
        function BindCounties() {

            //RESET ddlCounty
            $(ddlCounty).html("");
            $(ddlCounty).attr("disabled", "disabled");

            //RESET ddlParish
            $(ddlParish).html("");
            $(ddlParish).attr("disabled", "disabled");

            //RESET ddlZone
            $(ddlZone).html("");
            $(ddlZone).attr("disabled", "disabled");

            //GET IDs of District
            var idDistrict = $(ddlDistrict).val();

            //IF SELECTED District
            if (idDistrict != 0 || idDistrict == undefined) {

                //GET Counties via JSON
                $(ddlCounty).append($("<option></option>").val(0).html(loadingFeedback));

                $.getJSON(handlersPath + "/GetCounties.ashx?cid=" + idDistrict + "&withprop=" + showOnlyWithProperties.toString, function (Counties) {

                    if (Counties != null && Counties != "-1") {
                        $(ddlCounty).html("");
                        //APPEND Counties ddlCounty
                        var hasRecords = false;

                        if (emptyCounty != "") $(ddlCounty).append($("<option></option>").val(0).html(emptyCounty))
                        else $(ddlCounty).append($("<option></option>").val(0).html(""))

                        $.each(Counties, function () {
                            $(ddlCounty).append($("<option></option>").val(this['VALUE']).html(this['TEXT']));
                            hasRecords = true;
                        });

                        //ENABLE ddlCounty
                        if (hasRecords) {
                            $(ddlCounty).removeAttr("disabled");
                        }
                        ParseQueryString(qsCounty, ddlCounty);
                    }
                    else {
                        $(ddlCounty).html("");
                    }
                });
            }
        }

        //GetParishes
        function BindParishes(idCounty) {

            //RESET ddlParish
            $(ddlParish).html("");
            $(ddlParish).attr("disabled", "disabled");

            //RESET ddlZone
            $(ddlZone).html("");
            $(ddlZone).attr("disabled", "disabled");


            //IF SELECTED  County
            if (idCounty != 0 && idCounty != "") {

                //GET Parishes via JSON
                $(ddlParish).append($("<option></option>").val(0).html(loadingFeedback));
                $.getJSON(handlersPath + "/GetParishes.ashx?cid=" + idCounty + "&withprop=" + showOnlyWithProperties.toString, function (Parishes) {
                    if (Parishes != null && Parishes != "-1") {
                        $(ddlParish).html("");
                        //APPEND Parishes on ddlParish
                        var hasRecords = false;

                        if (emptyParish != "") $(ddlParish).append($("<option></option>").val(0).html(emptyParish))
                        else $(ddlParish).append($("<option></option>").val(0).html(""))

                        $.each(Parishes, function () {
                            $(ddlParish).append($("<option></option>").val(this['VALUE']).html(this['TEXT']));
                            hasRecords = true;
                        });

                        //ENABLE ddlParishs
                        if (hasRecords) {
                            $(ddlParish).removeAttr("disabled");
                        }

                        ParseQueryString(qsParish, ddlParish);


                    }
                    else {
                        $(ddlParish).html("");
                    }
                });
            }
        }

        function BindZones() {

            //RESET  ddlZone
            $(ddlZone).html("");
            $(ddlZone).attr("disabled", "disabled");

            //GET  ID select Parish
            var idParish = $(ddlParish).val();


            //IF SELECTED  County
            if (idParish != 0) {

                //GET Parishes via JSON
                $(ddlZone).append($("<option></option>").val(0).html(loadingFeedback));

                $.getJSON(handlersPath + "/GetZones.ashx?cid=" + idParish + "&withprop=" + showOnlyWithProperties.toString, function (Zones) {
                    if (Zones != null && Zones != "-1") {
                        $(ddlZone).html("");
                        //APPEND Zones in ddlZone
                        var hasRecords = false;

                        if (emptyZone != "") $(ddlZone).append($("<option></option>").val(0).html(emptyZone))
                        else $(ddlZone).append($("<option></option>").val(0).html(""))

                        $.each(Zones, function () {
                            $(ddlZone).append($("<option></option>").val(this['VALUE']).html(this['TEXT']));
                            hasRecords = true;
                        });

                        //ENABLE ddlParishs
                        if (hasRecords) {
                            $(ddlZone).removeAttr("disabled");
                        }

                        ParseQueryString(qsZone, ddlZone);
                    }
                    else {
                        $(ddlZone).html("");
                    }
                });
            }
        }

        function BindAreas(idGroup) {
            //RESET  Areas
            $(ddlMinArea).html("");
            $(ddlMinArea).attr("disabled", "disabled");

            $(ddlMaxArea).html("");
            $(ddlMaxArea).attr("disabled", "disabled");


            var selectValues = [];
            switch (parseInt(idGroup)) {
                case 0:
                case 222:
                case 223:
                    selectValues.push({ key: "0", value: 0 });
                    selectValues.push({ key: "100", value: 100 });
                    selectValues.push({ key: "150", value: 150 });
                    selectValues.push({ key: "200", value: 200 });
                    selectValues.push({ key: "250", value: 250 });
                    selectValues.push({ key: "300", value: 300 });
                    selectValues.push({ key: "350", value: 350 });
                    selectValues.push({ key: "400", value: 400 });
                    selectValues.push({ key: "450", value: 450 });
                    selectValues.push({ key: "500", value: 500 });
                    selectValues.push({ key: "550", value: 550 });
                    selectValues.push({ key: "600", value: 600 });
                    selectValues.push({ key: "650", value: 650 });
                    selectValues.push({ key: "700", value: 700 });
                    selectValues.push({ key: "750", value: 750 });
                    selectValues.push({ key: "800", value: 800 });
                    selectValues.push({ key: "850", value: 850 });
                    selectValues.push({ key: "900", value: 900 });
                    selectValues.push({ key: "950", value: 950 });
                    selectValues.push({ key: "1.000", value: 1000 });
                    selectValues.push({ key: "> 1.000", value: 0 });
                    break;
                case 1532:
                case 224:
                    selectValues.push({ key: "0", value: 0 });
                    selectValues.push({ key: "500", value: 500 });
                    selectValues.push({ key: "1.000", value: 1000 });
                    selectValues.push({ key: "1.500", value: 1500 });
                    selectValues.push({ key: "2.000", value: 2000 });
                    selectValues.push({ key: "2.500", value: 2500 });
                    selectValues.push({ key: "5.000", value: 5000 });
                    selectValues.push({ key: "10.000", value: 10000 });
                    selectValues.push({ key: "15.000", value: 15000 });
                    selectValues.push({ key: "20.000", value: 20000 });
                    selectValues.push({ key: "25.000", value: 25000 });
                    selectValues.push({ key: "30.000", value: 30000 });
                    selectValues.push({ key: "35.000", value: 35000 });
                    selectValues.push({ key: "40.000", value: 40000 });
                    selectValues.push({ key: "45.000", value: 45000 });
                    selectValues.push({ key: "50.000", value: 50000 });
                    selectValues.push({ key: "> 50.000", value: 0 });
                    break;
                case 225:
                    selectValues.push({ key: "0", value: 0 });
                    selectValues.push({ key: "100", value: 100 });
                    selectValues.push({ key: "150", value: 150 });
                    selectValues.push({ key: "200", value: 200 });
                    selectValues.push({ key: "250", value: 250 });
                    selectValues.push({ key: "300", value: 300 });
                    selectValues.push({ key: "350", value: 350 });
                    selectValues.push({ key: "400", value: 400 });
                    selectValues.push({ key: "450", value: 450 });
                    selectValues.push({ key: "500", value: 500 });
                    selectValues.push({ key: "750", value: 750 });
                    selectValues.push({ key: "1.000", value: 1000 });
                    selectValues.push({ key: "1.500", value: 1500 });
                    selectValues.push({ key: "2.000", value: 2000 });
                    selectValues.push({ key: "2.500", value: 2500 });
                    selectValues.push({ key: "5.000", value: 5000 });
                    selectValues.push({ key: "6.000", value: 6000 });
                    selectValues.push({ key: "7.000", value: 7000 });
                    selectValues.push({ key: "8.000", value: 8000 });
                    selectValues.push({ key: "9.000", value: 9000 });
                    selectValues.push({ key: "10.000", value: 10000 });
                    selectValues.push({ key: "> 10.000", value: 0 });
                    break;
            }

            $.each(selectValues, function () {
                var key = $(this).attr("key");
                var value = $(this).attr("value");
                $(ddlMinArea).
                      append($("<option></option>").
                      attr("value", value).
                      text(key));
                $(ddlMaxArea).
                      append($("<option></option>").
                      attr("value", value).
                      text(key));
            });

            $(ddlMinArea).removeAttr("disabled");
            $(ddlMaxArea).removeAttr("disabled");

            var lastIndexArea = $(ddlMaxArea + " option").index($(ddlMaxArea + " option:last"));
            $(ddlMaxArea + " option:eq(" + lastIndexArea + ")").attr("selected", "selected");

            ParseQueryString(qsMinArea, ddlMinArea);
            ParseQueryString(qsMaxArea, ddlMaxArea);

            SetupRangeField("minArea", "maxArea", "areaRange", isAreaSlider);
        }

        function BindPrices(idPurpose) {
            //RESET  Prices
            $(ddlMinPrice).html("");
            $(ddlMinPrice).attr("disabled", "disabled");

            $(ddlMaxPrice).html("");
            $(ddlMaxPrice).attr("disabled", "disabled");

            var selectValues = [];
            switch (parseInt(idPurpose)) {
                case 1516:
                case 241:
                    selectValues.push({ key: "0", value: 0 });
                    selectValues.push({ key: "250", value: 250 });
                    selectValues.push({ key: "350", value: 350 });
                    selectValues.push({ key: "450", value: 450 });
                    selectValues.push({ key: "500", value: 500 });
                    selectValues.push({ key: "1.000", value: 1000 });
                    selectValues.push({ key: "1.500", value: 1500 });
                    selectValues.push({ key: "2.000", value: 2000 });
                    selectValues.push({ key: "> 2.000", value: 0 });
                    break;
                case 0:
                default:
                    selectValues.push({ key: "0", value: 0 });
                    selectValues.push({ key: "25.000", value: 25000 });
                    selectValues.push({ key: "50.000", value: 50000 });
                    selectValues.push({ key: "75.000", value: 75000 });
                    selectValues.push({ key: "100.000", value: 100000 });
                    selectValues.push({ key: "150.000", value: 150000 });
                    selectValues.push({ key: "200.000", value: 200000 });
                    selectValues.push({ key: "> 200.000", value: 0 });
                    break;
            }

            $.each(selectValues, function () {
                var key = $(this).attr("key");
                var value = $(this).attr("value");
                $(ddlMinPrice).
                      append($("<option></option>").
                      attr("value", value).
                      text(key));
                $(ddlMaxPrice).
                      append($("<option></option>").
                      attr("value", value).
                      text(key));
            });

            $(ddlMinPrice).removeAttr("disabled");
            $(ddlMaxPrice).removeAttr("disabled");

            var lastIndexPrice = $(ddlMaxPrice + " option").index($(ddlMaxPrice + " option:last"));
            $(ddlMaxPrice + " option:eq(" + lastIndexPrice + ")").attr("selected", "selected");


            ParseQueryString(qsMinPrice, ddlMinPrice);
            ParseQueryString(qsMaxPrice, ddlMaxPrice);


            SetupRangeField("minPrice", "maxPrice", "priceRange", isPriceSlider);

        }

        //Setup the typology slider - if exists
        function BindTypologies() {
            var lastIndexTypology = $(ddlTypologyMax + " option").index($(ddlTypologyMax + " option:last"));
            $(ddlTypologyMax + " option:eq(" + lastIndexTypology + ")").attr("selected", "selected");
            SetupRangeField("minTypology", "maxTypology", "typologyRange", isTypologySlider);

        }

        //get a specified key of query string
        function ParseQueryString(key, control) {

            var id = $.jqURL.get(key);

            if (id != "undefined" && id != null) {


                if (key == qsDistrict || key == qsGroup) {
                    $(control).val(id.toString())
                }
                else {
                    if ($(control).css("display") != "none") { selectItem(id, control); }
                }

                switch (key) {
                    case qsDistrict: BindCounties(); break;
                    case qsCounty: BindParishes(id); break;
                    case qsParish: BindZones(); break;
                }
            }
        }

        //select the item of the control with the specified id  (can be string of ids
        function selectItem(id, control) {
            var idArray = id.split(',');
            var i = 0;
            for (i = 0; i < idArray.length; i++) {
                $("select#" + control + " option[value=" + idArray[i].toString() + "]").attr("selected", "selected");
            }
        }

        //Build the query string with the id of the field and the value. If the qString is empty, the token will be ?.
        function BuildQueryStringItem(qString, keyID, keyValue) {
            var qsToken = "&";
            if (qString == "") qsToken = "?"
            qString = qString + qsToken + keyID + "=" + keyValue;
            return qString;
        }

        //save the search in statistics
        function SendSearchToStats(qString) {
            $.getJSON(handlersPath + "/UpdateSearchStats.ashx" + qString, null);
        }

        //Verify if a list of values(mandatoryfields) are filled. if not, the submit is not valid
        function isSubmitValid(aValues) {
            var isValid = true;
            $(aValues).each(function () {
                if ($(this).val() <= 0 || $(this).val() == 'null') { isValid = false; }
                if (isValid == false) { return false; }
            });
            if (isValid == true) { return true; }
        }

        //Setup the sliders,if the control is a slider. if the control is already assign, that will be removed and added again
        function SetupRangeField(controlMin, controlMax, label, isSlider) {
            if (isSlider == "true" && $('select.' + controlMin + ', select.' + controlMax).css("display") != "none") {
                $('select.' + controlMin + ', select.' + controlMax).hide();
                var initialMinValue = $('select.' + controlMin + " option:first").text();
                var initialMaxValue = $('select.' + controlMin + " option:last").text();
                $("span." + label).text(initialMinValue + valuesSeparator + initialMaxValue);
                $('select.' + controlMin + ', select.' + controlMax).selectToUISlider({
                    labels: 0,
                    tooltip: false,
                    sliderOptions: {
                        change: function (e, ui) {
                            var minValue = $('select.' + controlMin + ' option').eq(ui.values[0]).text();
                            var maxValue = $('select.' + controlMax + ' option').eq(ui.values[1]).text();
                            $("span." + label).text(minValue + valuesSeparator + maxValue);
                        }
                    },
                    cssClass: label

                });
            } else {
                //alreadyExists
                if (isSlider == "true") {
                    var initialMinValue = $('select.' + controlMin + " option:first").text();
                    var initialMaxValue = $('select.' + controlMin + " option:last").text();
                    $("span." + label).text(initialMinValue + valuesSeparator + initialMaxValue);
                    $("div." + label).remove();
                    $('select.' + controlMin + ', select.' + controlMax).selectToUISlider({
                        labels: 0,
                        tooltip: false,
                        sliderOptions: {
                            change: function (e, ui) {
                                var minValue = $('select.' + controlMin + ' option').eq(ui.values[0]).text();
                                var maxValue = $('select.' + controlMax + ' option').eq(ui.values[1]).text();
                                $("span." + label).text(minValue + valuesSeparator + maxValue);
                            }
                        },
                        cssClass: label
                    });


                }

            }

        }
    });


}




