
    /* Cache version: 20121101 */
    /* Included files: rtslib/browser.js,rtslib/basic.js,rtslib/date.js */




    if (typeof RTS != 'object') 
    RTS = {};

(function(ns) {
    var ua = navigator.userAgent,
        browser = navigator.appVersion,
        lbrowser = browser.toLowerCase();
    
    ns.browser = {
        IE: window.attachEvent && !window.opera,
        Opera: !!window.opera,
        WebKit: ua.indexOf('AppleWebKit/') > -1,
        Gecko: ua.indexOf('Gecko') > -1 && ua.indexOf('KHTML') == -1,
        MobileSafari: ua.search(/Apple.*Mobile.*Safari/) != -1,
        IE6: browser.indexOf('MSIE 6') > -1,
        IE7: browser.indexOf('MSIE 7') > -1,
        IE8: browser.indexOf('MSIE 8') > -1,
        IE9: browser.indexOf('MSIE 9') > -1,
        IE10: browser.indexOf('MSIE 10') > -1,
        wMetro: (browser.indexOf('MSIE 10') > -1 && window.innerWidth == screen.width && window.innerHeight == screen.height) ? true : false,
        wPhone: lbrowser.indexOf('windows phone') > -1,
        safari: browser.indexOf('Safari') > -1,
        firefox: navigator.appName.indexOf('Netscape') > -1 && browser.indexOf('Safari') == -1,
        iOs: browser.indexOf('iPhone') > -1 || browser.indexOf('iPod') > -1 || browser.indexOf('iPad') > -1,
        iPhone: browser.indexOf('iPhone') > -1,
        iPad: browser.indexOf('iPad') > -1,
        iPod: browser.indexOf('iPod') > -1,
        symbian: lbrowser.indexOf('symbian') > -1,
        android: lbrowser.indexOf('android') > -1,
        legacyAndroid: /android 2.[012]/.test(lbrowser),
        mobile: browser.indexOf('iPhone') > -1 || browser.indexOf('iPod') > -1 || browser.indexOf('iPad') > -1 || lbrowser.indexOf('symbian') > -1 || lbrowser.indexOf('android') > -1,
        hasFlash: typeof(swfobject)=='object' && swfobject.getFlashPlayerVersion().major > 0,
        chrome: browser.indexOf('Chrome') > -1
    };
})(RTS);

if (typeof RTS != 'object')
	RTS = {};

RTS.basic = {
	init: function() {
		RTS.basic.clickAndHide('#rts-search'); // header
		RTS.basic.clickAndHide('#search-audio'); //iplayer
	},
	host: (!~document.location.href.search(/^https?:\/\/([^\/]*(ece[^.]*|www)\.)?(rts|tsr|rsr)\.ch/) ? window.location.protocol + '//www.rts.ch' : ''),
	www4Host: this.host == '' ? 'http://www.rts.ch/www4' : window.location.protocol + "//" + window.location.host + '/www4',
	publication: (
			(~document.location.href.search(/^https?:\/\/([^\/]*(ece[^.]*|www)\.)?tsr\.ch/) ? 'tsr' :
			(~document.location.href.search(/^https?:\/\/([^\/]*(ece[^.]*|www)\.)?rsr\.ch/) ? 'rsr' : 'rts'))
	),
	isDev: (~document.location.href.search(/([^\/]*(ecedev[^.]*)\.)/)) ? true : false,
	isStage: (~document.location.href.search(/([^\/]*(ecestage[^.]*)\.)/)) ? true : false,
    setCookie: function(name, value, expires, path,	domain,	secure) {
		// set time, it's in milliseconds
		var today = new	Date();
		today.setTime(today.getTime());

		var expires_date = new Date( today.getTime() + (expires));

		document.cookie = name + "=" + escape(value) +
		((expires) ? ";expires=" + expires_date.toGMTString() : "") +
		((path) ? ";path=" + path : "") +
		((domain) ?	";domain=" + domain : "") +
		((secure) ?	";secure" : "");
	},
	getCookie: function(name) {
		var a_all_cookies = document.cookie.split(';');
		var a_temp_cookie = '';
		var cookie_name = '';
		var cookie_value = '';
		var b_cookie_found = false;

		for ( i = 0; i < a_all_cookies.length; i++ ) {
			a_temp_cookie = a_all_cookies[i].split('=');
			cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
			if (cookie_name == name) {
				b_cookie_found = true;
				if (a_temp_cookie.length > 1) cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));

				return cookie_value;
				break;
			}
			a_temp_cookie = null;
			cookie_name = '';
		}
		if (!b_cookie_found) return null;
	},
	getUrlVars: function() {
		var vars = [], hash;
		var hashes = window.location.href.slice(window.location.href.indexOf('?') +	1).split('&');
		for(var i = 0; i < hashes.length; i++) {
			hash = hashes[i].split('=');
			vars.push(hash[0]);
			vars[hash[0]] = hash[1];
		}
		return vars;
	},

	/**
	 * Proxify url (authorized domains : rts.ch, tsr.ch, rsr.ch)
	 */
	ajxProxify: function(url) {
        var matches = url.match(/^https?:\/\/([^\/]*)/);
        if (null !== matches && document.location.host != matches[1] && matches[1].match(/(rts|rsr|tsr)\.ch$/))
            return "/?f=ajax/proxy&url=" + encodeURIComponent(url);

        return url;
	},

	/**
	@desc utilisé pour les browsers ne supportant pas l'attribut placeholder
	*/
	clickAndHide:function(jId) {
        var input = document.createElement('input');
        if(!('placeholder' in input)){
            var searchInput = $(jId);            
            var placeHolder = searchInput.attr('placeholder');
            searchInput.val(placeHolder);
            
            searchInput.on('focus', function(){
                if($(this).val() == placeHolder) { $(this).val(''); }
            }).on('blur', function(){
                if($(this).val() == '') { $(this).val(placeHolder); }
            });
        }        
	},
	openPopup:function(selector, option) {
		if(!option) option = {};

		//si pas de url	definie on utilise la valeur de l'attribue href
		if(!option.url)
			option.url = $(selector).attr("href");

		//fonction anonyme ouvrant la popup
		var open = function(option) {
			//sérialisation des options
			var rawOption = '';

			$.each(option, function(k,v) {
				if(k != 'url' && k != 'winName')
					rawOption +=k+'='+v+',';
			});
			//ouverture de la fenêtre
			window.open(option.url,	option.winName,	rawOption );
		}

		if(option.direct == true) {
			//execution en mode direct
			open(option);
		} else {
			//execution en mode event
			$(selector).click(function(e) {
				e.preventDefault();
				open(option);
			});
		}
	},
	getParam:function (n,s){
		var re = new RegExp("[\\?;#]"+n+"=([^;#]*)"),
			matches = re.exec(s);
		//log(n + ' ' + s + ' ' + (matches && matches[1]));
		return matches && matches[1];
	}
};
/**
 * Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601>
 * © 2011 Colin Snover <http://zetafleet.com>
 * Released under MIT license.
 */
(function (Date, undefined) {
    var origParse = Date.parse, numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ];
    Date.parse = function (date) {
        var timestamp, struct, minutesOffset = 0;

        // ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string
        // before falling back to any implementation-specific date parsing, so that’s what we do, even if native
        // implementations could be faster
        //              1 YYYY                2 MM       3 DD           4 HH    5 mm       6 ss        7 msec        8 Z 9 ±    10 tzHH    11 tzmm
        if ((struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date))) {
            // avoid NaN timestamps caused by “undefined” values being passed to Date.UTC
            for (var i = 0, k; (k = numericKeys[i]); ++i) {
                struct[k] = +struct[k] || 0;
            }

            // allow undefined days and months
            struct[2] = (+struct[2] || 1) - 1;
            struct[3] = +struct[3] || 1;

            if (struct[8] !== 'Z' && struct[9] !== undefined) {
                minutesOffset = struct[10] * 60 + struct[11];

                if (struct[9] === '+') {
                    minutesOffset = 0 - minutesOffset;
                }
            }

            timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]);
        }
        else {
            timestamp = origParse ? origParse(date) : NaN;
        }

        return timestamp;
    };
}(Date));

/**
 * RTS.date
 * Offers some usefull date handling functions.
 */
if (typeof RTS != 'object')
    RTS = {};

RTS.date = {
    init: function() {},
    
    /**
     * Returns formated date.
     * 
     * @param String            format  Output format (see strftime for more info on format).
     * @param Date|Int|String   d       Date to process (defaults to now).
     * @param Int               gmt     Timezone for display (defaults to user current timezone).
     * @return String
     */
    format: function(format, d, gmt) {
        if (!d) {
            d = new Date();
        } else if (typeof d == "string") {
            // Try preformating string like ddmmyyyy.
            d = d.replace(/^(\d{2})(\d{2})(\d{4})$/, "$3-$2-$1");
            d = this.parse(d);
        }
        
        if (typeof d == "number")
            d = new Date(d);
        
        var tzOffset = d.getTimezoneOffset();


        if (gmt !== undefined) {
            //tzOffset = -Math.abs(gmt)*60;
            tmpD = d.getTime() + (d.getTimezoneOffset() * 60000);
            d = new Date(tmpD + (3600000*gmt));
        }
        else {
            d.setTime(d.getTime() - (tzOffset*60*1000));
        }
        
        var replacements = {
            Y: d.getFullYear(),
            m: d.getMonth()+1,
            d: d.getDate(),
            H: d.getHours(),
            M: d.getMinutes(),
            S: d.getSeconds()
        };
        
        for (var k in replacements) {
            var v = replacements[k] < 10 ? '0' + replacements[k] : replacements[k];
            format = format.replace("%" + k, v);
        }
        return format;
    },


    /**
     * Returns difference between local time and swiss time (in hours).
     * 
     * @return Int
     */
    getSwitzerlandOffset : function() {
        var switzerlandOffset = 1;
        var rightNow = new Date();
        var dst;
        if (rightNow.dst()) {
            dst = 1; // daylight savings time is observed
        } else {
            dst = 0; // daylight savings time is NOT observed
        }

        return switzerlandOffset + dst;
    },
    
    /**
     * Parses a date and returns corresponding timestamp.
     * 
     * @param String value
     * @return Int
     */
    parse: function(value) {
        return Date.parse(value);
    }
};


Date.prototype.stdTimezoneOffset = function() {
    var jan = new Date(this.getFullYear(), 0, 1);
    var jul = new Date(this.getFullYear(), 6, 1);
    return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}

Date.prototype.dst = function() {
    return this.getTimezoneOffset() < this.stdTimezoneOffset();
}
