/* mpg javascript */

$( function() {
	
	init_lazyload();
	init_jqueryui_base();
	init_lightbox();
	/* custom mouseovers! */
	init_custom_mouseovers()
	
	/* special labels */
	$('body').addClass('has-js');
	$('.label_check, .label_radio').click(function(){
		setupLabel();
	});
	setupLabel();
	
});

function init_lazyload()
{
	/* image lazyload initiation */
    $(".lazyload").lazyload({
		placeholder : "/images/load_whiteback.gif",
		effect      : "fadeIn"
	});	
}

function init_lightbox()
{
	/* image lightbox initiation */
    /*
	$('a[rel*=facebox]').facebox({
		loadingImage : '/js/jquery/facebox/loading.gif',
		closeImage   : '/js/jquery/facebox/closelabel.png'
	});
	*/
	$(".lightbox").lightbox({
		fitToScreen: true,
		imageClickClose: false, 
		fileLoadingImage: '/js/jquery/plugins/lightbox_new/images/loading.gif',
		fileBottomNavCloseImage: '/js/jquery/plugins/lightbox_new/images/closelabel.gif', 
		resizeSpeed: 10, 
		loopImages: true
	});	
}

function init_jqueryui_base()
{
	$(".jquery_button").button();
	$(".jquery_buttonset").buttonset();
}

function init_custom_mouseovers()
{
	$('.custom_mouseover').mouseover( function() {
		tooltip_custom($(this).offset().left, ( $(this).offset().top + $(this).outerHeight() + 10), $(this).attr('rel'));
	}).mouseout( function() {
		tooltip_off();
	});
	$('.custom_mouseover_question').mouseover( function() {
		tooltip_custom_message($(this).offset().left, ( $(this).offset().top + $(this).outerHeight() + 10), $(this).attr('rel'));
	}).mouseout( function() {
		tooltip_off();
	});
}

function syncronous_load(ajaxUrl, targetID)
{
	$.ajax({
		url:ajaxUrl,
		async:false,
		success:function(a){
			$("#"+targetID).html(a);
			init_jqueryui_base()
		}
	});
	return true;
}

function setupLabel()
{
     if ($('.label_check input').length) {
         $('.label_check').each(function(){ 
             $(this).removeClass('c_on');
         });
         $('.label_check input:checked').each(function(){ 
             $(this).parent('label').addClass('c_on');
         });                
     };
     if ($('.label_radio input').length) {
         $('.label_radio').each(function(){ 
             $(this).removeClass('r_on');
         });
         $('.label_radio input:checked').each(function(){ 
             $(this).parent('label').addClass('r_on');
         });
     };
};


// custom tooltip
var loader_html = '<img src="/images/loading_medium_white.gif" alt="Loading..." title="Loading...">';

function tooltip_position(containerId, offsetDistance)
{
	// determine the offset
	$('#tooltip_ajax').css('display', 'inline');
	// preloader image
	$('#tooltip_ajax').html(loader_html);
	// position the window
	$('#tooltip_ajax').css('top', ( $('#'+containerId).offset().top + $('#'+containerId).outerHeight() + parseFloat(offsetDistance)) + 'px');
	$('#tooltip_ajax').css('left',  ( $('#'+containerId).offset().left + parseFloat(offsetDistance)) + 'px');
}

function tooltip(containerId, listingId, offsetDistance)
{
	tooltip_position(containerId, offsetDistance);
	// pull the content through ajax call
	$('#tooltip_ajax').load( '/ajax/ajax_tooltip?r&listingid=' + listingId );
	
}

function tooltip_custom(offsetLeft, offsetTop, listingId)
{
	// tooltip_position(containerId, offsetDistance);
	$('#tooltip_ajax').css('display', 'inline');
	$('#tooltip_ajax').css('left',  offsetLeft + 'px');
	$('#tooltip_ajax').css('top', offsetTop + 'px');
	// pull the content through ajax call
	$('#tooltip_ajax').load( '/ajax/ajax_tooltip?r&listingid=' + listingId );
	
}

function tooltip_custom_message(offsetLeft, offsetTop, messageText)
{
	// tooltip_position(containerId, offsetDistance);
	$('#tooltip_ajax').css('display', 'inline');
	$('#tooltip_ajax').css('left',  offsetLeft + 'px');
	$('#tooltip_ajax').css('top', offsetTop + 'px');
	/* make sure you're not off the screen to the right... */
	var thisOffset = offsetLeft + 340;
	if ( thisOffset > $(window).width() ) {
		$('#tooltip_ajax').css('left',  ( $(window).width() - 340 )  + 'px');	
	}
	// pull the content through ajax call
	$('#tooltip_ajax').html( messageText );
	
}

function tooltip_url(containerId, thumbUrl, offsetDistance)
{
	tooltip_position(containerId, offsetDistance);
	// pull the content through ajax call
	$('#tooltip_ajax').load( '/ajax/ajax_tooltip?bc&url=' + thumbUrl );	
}

function tooltip_warn(containerId, thumbUrl, offsetDistance)
{
	tooltip_position(containerId, offsetDistance);
	// pull the content through ajax call
	$('#tooltip_ajax').load('/ajax/ajax_tooltip?warn&url='+thumbUrl );	
}

function tooltip_calendar(containerId, calendarId, offsetDistance)
{
	tooltip_position(containerId, offsetDistance);
	// pull the content through ajax call
	$('#tooltip_ajax').load('/ajax/ajax_tooltip?calendarid='+calendarId );	
}

function tooltip_off()
{
	$('#tooltip_ajax').css('display', 'none');	
}

function str_replace (search, replace, subject, count) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order
    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'
    var i = 0,
        j = 0,
        temp = '',
        repl = '',
        sl = 0,
        fl = 0,
        f = [].concat(search),
        r = [].concat(replace),
        s = subject,
        ra = Object.prototype.toString.call(r) === '[object Array]',
        sa = Object.prototype.toString.call(s) === '[object Array]';
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i = 0, sl = s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j = 0, fl = f.length; j < fl; j++) {
            temp = s[i] + '';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length - s[i].length) / f[j].length;
            }
        }
    }
    return sa ? s : s[0];
}

/* php.js functions */

function strstr (haystack, needle, bool) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: strstr('Kevin van Zonneveld', 'van');
    // *     returns 1: 'van Zonneveld'
    // *     example 2: strstr('Kevin van Zonneveld', 'van', true);
    // *     returns 2: 'Kevin '
    // *     example 3: strstr('name@example.com', '@');
    // *     returns 3: '@example.com'
    // *     example 4: strstr('name@example.com', '@', true);
    // *     returns 4: 'name'
    var pos = 0;

    haystack += '';
    pos = haystack.indexOf(needle);
    if (pos == -1) {
        return false;
    } else {
        if (bool) {
            return haystack.substr(0, pos);
        } else {
            return haystack.slice(pos);
        }
    }
}

function rand (min, max) {
    // http://kevin.vanzonneveld.net
    // +   original by: Leslie Hoare
    // +   bugfixed by: Onno Marsman
    // %          note 1: See the commented out code below for a version which will work with our experimental (though probably unnecessary) srand() function)
    // *     example 1: rand(1, 1);
    // *     returns 1: 1
    var argc = arguments.length;
    if (argc === 0) {
        min = 0;
        max = 2147483647;
    } else if (argc === 1) {
        throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
    }
    return Math.floor(Math.random() * (max - min + 1)) + min;

/*
    // See note above for an explanation of the following alternative code
    
    // +   reimplemented by: Brett Zamir (http://brett-zamir.me)
    // -    depends on: srand
    // %          note 1: This is a very possibly imperfect adaptation from the PHP source code
    var rand_seed, ctx, PHP_RAND_MAX=2147483647; // 0x7fffffff

    if (!this.php_js || this.php_js.rand_seed === undefined) {
        this.srand();
    }
    rand_seed = this.php_js.rand_seed;

    var argc = arguments.length;
    if (argc === 1) {
        throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
    }

    var do_rand = function (ctx) {
        return ((ctx * 1103515245 + 12345) % (PHP_RAND_MAX + 1));
    };

    var php_rand = function (ctxArg) { // php_rand_r
        this.php_js.rand_seed = do_rand(ctxArg);
        return parseInt(this.php_js.rand_seed, 10);
    };

    var number = php_rand(rand_seed);

    if (argc === 2) {
        number = min + parseInt(parseFloat(parseFloat(max) - min + 1.0) * (number/(PHP_RAND_MAX + 1.0)), 10);
    }
    return number;
    */
}

function strip_tags (input, allowed) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Luke Godfrey
    // +      input by: Pul
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +      input by: Alex
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Marc Palau
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Eric Nagel
    // +      input by: Bobby Drake
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Tomasz Wesolowski
    // +      input by: Evertjan Garretsen
    // +    revised by: Rafal Kukawski (http://blog.kukawski.pl/)
    // *     example 1: strip_tags('<p>Kevin</p> <br /><b>van</b> <i>Zonneveld</i>', '<i><b>');
    // *     returns 1: 'Kevin <b>van</b> <i>Zonneveld</i>'
    // *     example 2: strip_tags('<p>Kevin <img src="someimage.png" onmouseover="someFunction()">van <i>Zonneveld</i></p>', '<p>');
    // *     returns 2: '<p>Kevin van Zonneveld</p>'
    // *     example 3: strip_tags("<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>", "<a>");
    // *     returns 3: '<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>'
    // *     example 4: strip_tags('1 < 5 5 > 1');
    // *     returns 4: '1 < 5 5 > 1'
    // *     example 5: strip_tags('1 <br/> 1');
    // *     returns 5: '1  1'
    // *     example 6: strip_tags('1 <br/> 1', '<br>');
    // *     returns 6: '1  1'
    // *     example 7: strip_tags('1 <br/> 1', '<br><br/>');
    // *     returns 7: '1 <br/> 1'
    allowed = (((allowed || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
    var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
        commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
    return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
        return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
    });
}

