var xp1script = "http://s.xp1.ru4.com/meta?_o=89362&_t=content";
var t;

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
(function ($) {
	var isObject = function (x) {
		return (typeof x === 'object') && !(x instanceof Array) && (x !== null);
	};
	
	$.extend({
		getJSONCookie: function (cookieName) {
			var cookieData = $.cookie(cookieName);
			return cookieData ? JSON.parse(cookieData) : {};
		},
		setJSONCookie: function (cookieName, data, options) {
			var cookieData = '';
			
			options = $.extend({
				expires: 90,
				path: '/'
			}, options);
			
			if (!isObject(data)) {	// data must be a true object to be serialized
				throw new Error('JSONCookie data must be an object');
			}
			try {
				cookieData = JSON.stringify(data);
			} catch(e) {}
			return $.cookie(cookieName, cookieData, options);
		},
		removeJSONCookie: function (cookieName) {
			return $.cookie(cookieName, null);
		},
		JSONCookie: function (cookieName, data, options) {
			if (data) {
				$.setJSONCookie(cookieName, data, options);
			}
			return $.getJSONCookie(cookieName);
		}
	});
})(jQuery);



function makePersistant(data){
	$.JSONCookie('x1persist', data, {expires:''})
}
function isPersistant() {
	var isPersistant = false;
	
	if($.cookie('x1persist')) {
		isPersistant = true;
	}
	return isPersistant;
}
function getXP1() {
	xp1script = xp1script + "&ssv_random=" + Math.floor(Math.random()*100)
	t = setTimeout("runDefault()", 1000);
	if(isPersistant()) {
		clearTimeout(t);
		loadedContent($.JSONCookie('x1persist'));
	}
	else {
		$.ajax({
			async: false,
			url: xp1script,
			dataType: "jsonp",
			jsonp: 'ssv_callback',
			success: function(data, textStatus, XMLHttpRequest) {
				clearTimeout(t);
				makePersistant(data);
				loadedContent(data);
			}
		});
	}
}

function loadedContent(data) {
	$.each(data, function(key, value) {
		setContent(key, value.creative, value.clicktrack);
	});	
}
function runDefault() {
	clearTimeout(t);
	makePersistant(defaultBAU);
	loadedContent(defaultBAU);
}
var itemsLoaded = 0;
function finishLoading(id) {
	itemsLoaded += 1;
	if(itemsLoaded == 3) {
		showContents()
	}
}

function showContents() {
	$(".content_background").show();
	$("#footer").show();
	$("#subfooter").show();
}

function setContent(id, itm, clk) {
	$("#" + id).ready(function() {
		var content = getContent(itm, id);
		if(content != null) {
			jQuery.ajax({
				async:false,
				url: content,
				dataType: "text",
				success: function(data, textStatus, XMLHttpRequest) {
						processData(data, id, itm, clk);
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					jQuery.ajax({
						async:false,
						url: getContent('', id),
						dataType: "text",
						success: function(data, textStatus, XMLHttpRequest) {
							processData(data, id, itm, clk);
						}
					});
				}
			});
		}
	});
}
function changeAnchors(id, clickTrack) {
	$("a", "#" + id).each(function() {
		if(this.href.indexOf("#") == -1 && this.href.indexOf("javascript") == -1) {
			this.href = clickTrack + "" + this.href;
		}
	});
};
function iframeLoaded(id, parentid, clk) {
	try {
		var iframe = $("#" + id);
		var elem = document.getElementById(id);
		var str = elem.contentWindow.getStr();
		iframe.parent().html(str);
		changeAnchors(parentid, clk);
		finishLoading(id);
	} catch(e) {}
};
function iframeInit(data, parentid, clk) {
	var idIndexStart = data.indexOf("id=\"") + 4;
	var idIndexStop = data.indexOf("\"", idIndexStart);
	var iframeid = data.slice(idIndexStart, idIndexStop);
	$("#" + parentid).append("<iframe style='display: none;' onload='iframeLoaded(this.id, \"" + parentid + "\", \"" + clk +"\")' id='" + iframeid + "'></iframe>");
	var iframe2 = document.getElementById(iframeid);
	ifrm = (iframe2.contentWindow) ? iframe2.contentWindow : (iframe2.contentDocument.document) ? iframe2.contentDocument.document : iframe2.contentDocument;
	ifrm.document.open();
	ifrm.document.write(data);
	ifrm.document.close();
	ifrm.document.innerHTML = data;
};

function processData(data, id, itm, clk) {
	if(data.indexOf("adtag") > -1) {
		iframeInit(data, id, clk);
	} else {
		$("#" + id).html(data);
		changeAnchors(id, clk);
		finishLoading(id);
	}
}


var defaultBAU = {
		"xpp1": {
			"creative": "rhs_accord_airhotel_hotel_show",
			"clicktrack": "http://s.xp1.ru4.com/click?_o=89362&_c=89363&_x=89369&_b=143199&_d=0&_g=143193&_a=143183&_p=89378&_s=0&_pm=0&_pn=0&_pl=0&ssv_creative1=143182&ssv_creative2=143183&ssv_creative3=143184&redirect="
		},
		"xpp2": {
			"creative": "lhs_flash_air_geo",
			"clicktrack": "http://s.xp1.ru4.com/click?_o=89362&_c=89363&_x=89369&_b=143202&_d=0&_g=143192&_a=143184&_p=89379&_s=0&_pm=0&_pn=0&_pl=0&ssv_creative1=143182&ssv_creative2=143183&ssv_creative3=143184&redirect="
		}
};

getXP1();

