// Javascript

if(document.location.toString().indexOf('http://cbq')!= -1){
	var STATIC_URL = 'http://cbq/';
}else{
	var STATIC_URL = 'http://www.chalets.qc.ca/';
}
if(!type_annonce){ var type_annonce = 0;}

$(function(){
	if($('.leftside_admin').length==0){ 
		if(document.location.toString().indexOf('recherche_avancee') != -1){
			$('a:eq(1)','#leftside').css({'color':'#FFF'});
		}else{
			$('a:eq(0)','#leftside').css({'color':'#FFF'});
		}
	}
	$('a[title]').tooltip({ 
		track: true, 
		delay: 0, 
		showURL: false, 
		showBody: " - ",
		fade: 250 
	});
	$('#infoTP a').tooltip({ 
		track: true, 
		delay: 0, 
		showURL: false, 
		showBody: " - ", 
		fade: 250 
	});

 
	$("#aideGM").dialog({
			autoOpen: false,
			height: 930,
			width: 610,
			modal: true
			
			
	 });
		
	$("#LinkAideGM").click(function () { 
		$('#aideGM').dialog('open');
		return false;
	});


		   
	$("#dialog_contact").dialog({
			autoOpen: false,
			height: 970,
			width: 600,
			modal: true,
			buttons: {
				'Envoyer': function() {
					var contactnom = $('#contactnom').val();
					var contactcourriel = $('#contactcourriel').val();
					var contactsujet = $('#contactsujet').val();
					var contacttxtarea = $('#contacttxtarea').val();
					var contactsecureimg = $('#contactsecureimg').val();
					
					if(contactnom.length==0){alert('Veuillez inscrire votre nom'); return false;}
					if(contactcourriel.length==0){alert('Veuillez inscrire votre courriel'); return false;}
					if(contactsujet.length==0){alert('Veuillez inscrire le sujet'); return false;}
					if(contacttxtarea.length==0){alert('Veuillez inscrire le message'); return false;}
					if(contactsecureimg.length==0){alert('Veuillez confirmer le code de sécurité'); return false;}
					
					$.post(STATIC_URL+'ajax/nousjoindre/',{'nom':contactnom, 'courriel':contactcourriel, 'sujet':contactsujet, 'txtarea':contacttxtarea, 'secureimg':contactsecureimg },function(p_data){
						if(p_data.res==true){
							alert('Message envoyé avec succès.');
							$("#dialog_contact").dialog('destroy');
						}else{
							alert(p_data.msg);
						}
					},'json');
				}
			}
	 });
	
		$('span.ui-icon').html('');

	$("a:eq(2)").click(function(){
		$('#dialog_contact').dialog('open');
		return false;
	});

/*
	$(window).scroll(function(){   
		$('#footrightmsg').stop().animate({'bottom':-$(document).scrollTop()},function(){$('#footrightmsg').effect("pulsate", { times:1 }, 250)});
	});
	*/

	$('input[type=radio]', '#leftside').click(function(e){
		if($(e.target).parents('label').index()==0){
			$('.forsale', '#leftside').hide();
			$('.forrent', '#leftside').show();
		}else if($(e.target).parents('label').index()==1){
			$('.forrent', '#leftside').hide();
			$('.forsale', '#leftside').show();
		}else{
			$('.forrent', '#leftside').hide();
			$('.forsale', '#leftside').hide();
		}

	}).eq(type_annonce).click();


	$('#header').fadeIn(500, function() {
		 $('#rotation img:first').fadeIn(1000, function() {
			$('#rotation').cycle();
		});
	});

	
	$('#loginemail', '#header').Watermark ('Courriel');
	$('#loginpasswd', '#header').Watermark ('Mot de passe');

	$('#loginemail2', '#middle').Watermark ('Courriel');
	$('#loginpasswd2', '#middle').Watermark ('Mot de passe');


	$('.titre', 'body#home').corner ('top');

$('.rotation').each(function(){
		var navcol = '#navcol'+$(this).attr('id');
		////		console.log(navcol);
		var itm = $(this);
		$(this).cycle({
		'fx':    'fade', 
		'timeout':2500,
		/*'cssAfter': {'opacity':'1'},
		'cssAfter': {'z-index':'0','display':'none'},*/
		'speed':  2500,
		'pager':  navcol,
		 pagerAnchorBuilder: pagerFactory,
		//pager:  $('.navcol', $(this).next()),
		pagerClick: function(){ $(itm).cycle("pause");/* //console.log($(this));*/}/**/
	}).cycle("pause");
		


	});
	/*** ONGLETS ***/
		$('.alinklouer', '#ongul').click(function(){
		$($('.smsearchchk')[0]).click();
		$('#FRM_RR').attr({'action':$('#FRM_RR').attr('action')+'?carte=1'}).submit();
		return false;
	});
	$('.alinkvendre', '#ongul').click(function(){
		$($('.smsearchchk')[1]).click();
		$('#FRM_RR').attr({'action':$('#FRM_RR').attr('action')+'?carte=1'}).submit();
		return false;
	});
	
	$('#LIbulletin').click(function(p_evt){
		$('#CHK_join').attr('checked', true);
		$('#bg-popup-bulletin').toggle();
		return false;
	});
	
	$('#BTN_joinnewsletter').click(function(p_evt){
				
			if( $('#bltnom').val() == 'Nom' || $('#bltnom').val() == '' || 
            $('#bltprenom').val() == 'Prénom' || $('#bltprenom').val() == '' || 
            $('#bltemail').val() == 'Courriel' || $('#bltemail').val() == '' || 
            $('#bltcat').val()=='' ){
					alert('Veuillez remplir tous les champs');
					return false;
				}
											
											
		if(! $('#CHK_join').attr('checked')){ $('#bg-popup-bulletin').toggle('blind'); return false; }
		
			$('#bltformDIV').fadeOut('fast');
			$('#bltformIndicator').fadeIn('slow');
			
			
			$.post('<?php print(WEB_URL);?>PAXServerVisitors/', {'nom':$('#bltnom').val(),'prenom':$('#bltprenom').val(),'email':$('#bltemail').val(),'cat':$('#bltcat').val(), 'act': 'JOINNl'  }, function(p_data){
			if(p_data.err){
				alert(p_data.err);
				$('#bltformIndicator').html('<span style="color:#990000">Impossible de Sauvegarder,Veuillez réessayer plus tardMerci.</span>').hide(2000);
				$('#bltformDIV').show(2000);
				return false;
			}
			$('#bltformIndicator').html('<span style="color:#456138"><strong>Merci de vous être abonné à notre bulletin de nouvelles.</strong></span>');
		},'json');
		
			
			
		
		
		
	});

	/*** ONGLETS ***/
	
	
	$('div.titre>span','#FRM_ADVSEARCH').corner('top');
	$('.alouer .titre','body#recherche-avancee').corner('top');
	$('.avendre .titre','body#recherche-avancee').corner('top');
	 
	
	/*** LOGIN ***/
	$('#logme').click(function(){
		$('#login01').submit();
	});
	$('#logme2').click(function(){
		$('#login02').submit();
	});
	$('#login01').submit(function(){
		if($('#loginemail').val()=='' || $('#loginemail').val()=='Courriel'){
			alert('Impossible de vous connecter, Veuillez fournir une adresse de courriel valide.');
			return false;
		}
		if($('#loginpasswd').val()=='' || $('#loginpasswd').val()=='Mot de passe'){
			alert('Impossible de vous connecter, Veuillez fournir un mot de passe valide.');
			return false;
		}
		
		$.post(STATIC_URL + 'ajax/login/', {'email': $('#loginemail').val(), 'password': $('#loginpasswd').val() }, function(p_data){
			//console.log(p_data);
			if(p_data.res==false){
				alert(p_data.err);
				return false;
			}
			window.location = STATIC_URL+'membres/';
		},'json');
		
		return false;
	});

	$('#login02').submit(function(){
		if($('#loginemail2').val()=='' || $('#loginemail2').val()=='Courriel'){
			alert('Impossible de vous connecter, Veuillez fournir une adresse de courriel valide.');
			return false;
		}
		if($('#loginpasswd2').val()=='' || $('#loginpasswd2').val()=='Mot de passe'){
			alert('Impossible de vous connecter, Veuillez fournir un mot de passe valide.');
			return false;
		}
		
		$.post(STATIC_URL+'ajax/login/',{'email':$('#loginemail2').val(), 'password':$('#loginpasswd2').val() }, function(p_data){
			//console.log(p_data);
			if(p_data.res==false){
				alert(p_data.err);
				return false;
			}
			window.location = STATIC_URL+'membres/';
		},'json');
		
		return false;
	});

	
	
});
function pagerFactory(idx, slide) {

	var m=idx;
	//if(idx==0){//console.log(idx); $m='';}
	var s = idx > 9 ? ' style="display:none"' : '';
	return ' <'+'a href="#"'+s+'>'+(idx+1)+'<'+'/a>';
};


/***************************************************
STRIP HTML TAGS
****************************************************/
function strip_tags(html){

	//PROCESS STRING
	if(arguments.length < 3) {
		html=html.replace(/<\/?(?!\!)[^>]*>/gi, '');
	} else {
		var allowed = arguments[1];
		var specified = eval("["+arguments[2]+"]");
		if(allowed){
			var regex='</?(?!(' + specified.join('|') + '))\b[^>]*>';
			html=html.replace(new RegExp(regex, 'gi'), '');
		} else{
			var regex='</?(' + specified.join('|') + ')\b[^>]*>';
			html=html.replace(new RegExp(regex, 'gi'), '');
		}
	}

	
	return html;
}

uniqid = (function () {
	var id = 0;
	return function () {
		var mystr = String((new Date()).getTime()).replace(/\D/gi,'');
		return mystr+'_'+id++;
	};
})();

function serialize (mixed_value) {

    var _getType = function (inp) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            match = cons.match(/(\w+)\(/);
            if (match) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';
    
    switch (type) {
        case "function": 
            val = ""; 
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            mixed_value = this.utf8_encode(mixed_value);
            val = "s:" + encodeURIComponent(mixed_value).replace(/%../g, 'x').length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            /*
            if (type == "object") {
                var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {
                    return;
                }
                objname[1] = this.serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }
            */
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") { 
                    continue; 
                }
                
                okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
                vals += this.serialize(okey) +
                        this.serialize(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
        case "undefined": // Fall-through
        default: // if the JS object has a property which contains a null value, the string cannot be unserialized by PHP
            val = "N";
            break;
    }
    if (type != "object" && type != "array") {
        val += ";";
    }
    return val;
}

function unserialize (data) {

    var that = this;
    var utf8Overhead = function(chr) {
        // http://phpjs.org/functions/unserialize:571#comment_95906
        var code = chr.charCodeAt(0);
        if (code < 0x0080) {
            return 0;
        }
        if (code < 0x0800) {
             return 1;
        }
        return 2;
    };


    var error = function (type, msg, filename, line){throw new that.window[type](msg, filename, line);};
    var read_until = function (data, offset, stopchr){
        var buf = [];
        var chr = data.slice(offset, offset + 1);
        var i = 2;
        while (chr != stopchr) {
            if ((i+offset) > data.length) {
                error('Error', 'Invalid');
            }
            buf.push(chr);
            chr = data.slice(offset + (i - 1),offset + i);
            i += 1;
        }
        return [buf.length, buf.join('')];
    };
    var read_chrs = function (data, offset, length){
        var buf;

        buf = [];
        for (var i = 0;i < length;i++){
            var chr = data.slice(offset + (i - 1),offset + i);
            buf.push(chr);
            length -= utf8Overhead(chr); 
        }
        return [buf.length, buf.join('')];
    };
    var _unserialize = function (data, offset){
        var readdata;
        var readData;
        var chrs = 0;
        var ccount;
        var stringlength;
        var keyandchrs;
        var keys;

        if (!offset) {offset = 0;}
        var dtype = (data.slice(offset, offset + 1)).toLowerCase();

        var dataoffset = offset + 2;
        var typeconvert = function(x) {return x;};

        switch (dtype){
            case 'i':
                typeconvert = function (x) {return parseInt(x, 10);};
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case 'b':
                typeconvert = function (x) {return parseInt(x, 10) !== 0;};
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case 'd':
                typeconvert = function (x) {return parseFloat(x);};
                readData = read_until(data, dataoffset, ';');
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 1;
            break;
            case 'n':
                readdata = null;
            break;
            case 's':
                ccount = read_until(data, dataoffset, ':');
                chrs = ccount[0];
                stringlength = ccount[1];
                dataoffset += chrs + 2;

                readData = read_chrs(data, dataoffset+1, parseInt(stringlength, 10));
                chrs = readData[0];
                readdata = readData[1];
                dataoffset += chrs + 2;
                if (chrs != parseInt(stringlength, 10) && chrs != readdata.length){
                    error('SyntaxError', 'String length mismatch');
                }

                // Length was calculated on an utf-8 encoded string
                // so wait with decoding
                readdata = that.utf8_decode(readdata);
            break;
            case 'a':
                readdata = {};

                keyandchrs = read_until(data, dataoffset, ':');
                chrs = keyandchrs[0];
                keys = keyandchrs[1];
                dataoffset += chrs + 2;

                for (var i = 0; i < parseInt(keys, 10); i++){
                    var kprops = _unserialize(data, dataoffset);
                    var kchrs = kprops[1];
                    var key = kprops[2];
                    dataoffset += kchrs;

                    var vprops = _unserialize(data, dataoffset);
                    var vchrs = vprops[1];
                    var value = vprops[2];
                    dataoffset += vchrs;

                    readdata[key] = value;
                }

                dataoffset += 1;
            break;
            default:
                error('SyntaxError', 'Unknown / Unhandled data type(s): ' + dtype);
            break;
        }
        return [dtype, dataoffset - offset, typeconvert(readdata)];
    };
    
    return _unserialize((data+''), 0)[2];
}

function utf8_encode ( argString ) {

    var string = (argString+''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");

    var utftext = "";
    var start, end;
    var stringl = 0;

    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;

        if (c1 < 128) {
            end++;
        } else if (c1 > 127 && c1 < 2048) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }

    if (end > start) {
        utftext += string.substring(start, string.length);
    }

    return utftext;
}

function utf8_decode ( str_data ) {

    var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;
    
    str_data += '';
    
    while ( i < str_data.length ) {
        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if ((c1 > 191) && (c1 < 224)) {
            c2 = str_data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }

    return tmp_arr.join('');
}



function htmlentities (string, quote_style) {

    var hash_map = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
    hash_map["'"] = '&#039;';
    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }
    
    return tmp_str;
}

function get_html_translation_table (table, quote_style) {
    
    var entities = {}, hash_map = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';

    useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';

    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: "+useTable+' not supported');
        // return false;
    }

    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {
        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';
        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';
        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';
        entities['175'] = '&macr;';
        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';
        entities['180'] = '&acute;';
        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';
        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';
        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';
        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';
        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';
        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';
        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';
        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';
        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';
        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';
        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';
        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';
        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';
        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';
        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';
        entities['255'] = '&yuml;';
    }

    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;';


    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        hash_map[symbol] = entities[decimal];
    }
    
    return hash_map;
}

