jQuery(function() {
	jQuery(document).ready(function() {
	//get GC if suumo sub domain
	if(document.domain.indexOf('.suumo.jp') > 0 && document.domain.indexOf('wwwtst.suumo.jp') < 0){
		var tsumekae_kun_url = 'http://suumo.jp/edit/slab/beacon/cpcookie.php';
		var ifr = document.createElement("iframe");
		ifr.style.display = "none";

		var targetNode = window.document.getElementsByTagName("script")[0];
		var getgcDiv = document.getElementById('PiroPiroGetSuumoGc');
		if (getgcDiv == null) {
			targetNode.parentNode.insertBefore(ifr, targetNode);
		} else {
			var firstChild = getgcDiv.firstChild;
			if (firstChild == null) {
				getgcDiv.appendChild(ifr);
			} else {
				getgcDiv.insertBefore(ifr, firstChild);
			}
		}

		ifr.onload = function() {
			goPiro2();
		};

		//for IE
		ifr.onreadystatechange = function() {
			if (this.readyState == "loaded" || this.readyState == "complete") {
				goPiro2();
			}
		};

		ifr.contentWindow.document.write('<body><script type="text/javascript" src="' + tsumekae_kun_url + '"></script></body>');

		ifr.contentWindow.document.close();
	} else {
		goPiro2();
	}

	function goPiro2() {

		if(ieCheck() === 6){
			return;
		}
		
		// var api_url = 'http://RecommendWebAPI-938690743.ap-northeast-1.elb.amazonaws.com';
		var api_url = (location.hostname.lastIndexOf('haishin-contents-kaihatsu',0) == -1) ? 'http://RecommendWebAPI-938690743.ap-northeast-1.elb.amazonaws.com' : 'http://dev-recommendwebapi-1323686225.ap-northeast-1.elb.amazonaws.com';

		var client_filter_name = jQuery("#client_filter_name").text();
		
		var client_filter_url = api_url + '/api/filters/customer_action2/' + client_filter_name;
		var req_params = location.search;
		var staging = false;
		if (req_params && req_params.match(/[?&]recommendstaging=true(&.*)?$/i)) {
			client_filter_url += '/stage';
			staging = true;
		}
		
		jQuery.ajax({
			url: client_filter_url,
			dataType: 'jsonp',
			jsonp: 'callback',
			scriptCharset: 'utf-8',
			cache: false,
			timeout: 5000,
			async: true,
			success: function(client_filter) {
				if (client_filter && client_filter.length > 0) {
					//Inlitialize
					var my_client_filter;
					var galileo_cookie;
					var impression_count = 0;
					
					function init(){
						var i;
						function getMyClientFilter(){
							var pathname = location.pathname;
							var option = [];
							var rand;
							if(client_filter){
								for(i = 0; i<client_filter.length; i++){
									if(pathname.indexOf(client_filter[i].location) === 0){
										option.push(client_filter[i]);
									}
								}
								if(option.length > 0){
									rand = Math.floor(Math.random() * option.length);
									return option[rand];
								}else{
									return null;
								}
							}else{
								return null;
							}
						}
						my_client_filter = getMyClientFilter();
						
						function inBlackList(){
							var blacklist = my_client_filter.blacklist;
							var pathname = location.pathname;
							if(blacklist && blacklist.length > 0){
								for(i = 0; i<blacklist.length; i++){
									if(pathname.indexOf(blacklist[i]) !== -1 ){
										return true;
									}
								}
							}
							return false;
						}
						if(my_client_filter && inBlackList()){
							my_client_filter = null;
						}

						function getGalileoCookie(){
							var my_suumo_gc = null;
							var gcName = 'GalileoCookie';
							if(document.domain.indexOf('.suumo.jp') > 0 && document.domain.indexOf('wwwtst.suumo.jp') == -1){
								gcName = '__wk_GC';
							}
							if(document.cookie && document.cookie.indexOf(gcName) !== -1){
								var cookies = document.cookie.split('; ');
								for (i=0; i<cookies.length; i++){
									var str = cookies[i].split("=");
									if (str[0] === gcName){
										my_suumo_gc = str[1];
									}
								}
							}
							return my_suumo_gc;
						}
						galileo_cookie = getGalileoCookie();

					}
					
					init();
					if(my_client_filter === null){
						//window.alert('no setting for ' + location.pathname);
						return;
					}
					
					if(my_client_filter.test_galileo_cookie){
						galileo_cookie = my_client_filter.test_galileo_cookie;
					}
					
					if(galileo_cookie === null){
						//window.alert('no GalileoCookie');
						return;
					}
					
					if(document.cookie.indexOf('__pppsc=') === -1){
						document.cookie = '__pppsc=0; path=' + my_client_filter.location + ';';
					}

					switch(my_client_filter.contents.creative_no) {
						case 3:
							break;
						case 2:
							break;
						case 1:
						default:
							jQuery.extend(jQuery.gritter.options, {
								position: 'bottom-right',
								fade_in_speed: (my_client_filter.display.start.fade_in_millis !== undefined) ? my_client_filter.display.start.fade_in_millis: 500,
								fade_out_speed: (my_client_filter.display.end.fade_out_millis !== undefined) ? my_client_filter.display.end.fade_out_millis: 500,
								time: (my_client_filter.display.end.timeout_millis !== undefined) ? my_client_filter.display.end.timeout_millis: 60000,
								space_num: (my_client_filter.display.start.drop_height !== undefined) ? my_client_filter.display.start.drop_height : 5,
								space_time: (my_client_filter.display.start.drop_time !== undefined) ? my_client_filter.display.start.drop_time : 100,
								slide_in_speed: (my_client_filter.display.start.slide_in_speed !== undefined) ? my_client_filter.display.start.slide_in_speed : 0
							});
							break;
					}

					//Functions
					var server_filter_args = {
						uu_id: galileo_cookie,
						ryoiki: my_client_filter.ryoiki,
						system_id: ['xjj-ol-front','mobile-ol-front','PC_SUUMO_HJ'],
						bs: my_client_filter.bs,
						duration: (my_client_filter.data_duration !== undefined) ? my_client_filter.data_duration : 30,
						average: 0
					};

					function clickLog(sendData){
							jQuery.ajax( {
									url: api_url + '/log/click',
									dataType: 'jsonp',
									jsonp: 'callback',
									scriptCharset: 'utf-8',
									cache: false,
									timeout: 2000,
									async: false,
									data: sendData
							});
					}

					function impressionLog(sendData){
							jQuery.ajax({
									url: api_url + '/log/impression',
									dataType: 'jsonp',
									jsonp: 'callback',
									scriptCharset: 'utf-8',
									cache: false,
									timeout: 2000,
									async: true,
									data: sendData
							});
					}

					function callServerFilter(){
						if(!my_client_filter.display.start.once || document.cookie.indexOf('__pppsc=1') === -1){
							setTimeout(function() {
								jQuery.ajax({
									url: api_url + '/api/filters/customer_action2?filter_args=' + encodeURIComponent(JSON.stringify(server_filter_args)),
									dataType: 'jsonp',
									jsonp: 'callback',
									scriptCharset: 'utf-8',
									cache: false,
									timeout: 5000,
									async: true,
									success: function(data) {
										if (data.result.message.user_id !== undefined) {
											subscribe(data.result.message);
										}
									},
									error: function() {
									}
								});
							},
							my_client_filter.display.start.delay_millis);
						}
					}
					
					function subscribe(data) {
						var threshold_check = true;
						for (var i in my_client_filter.threshold) {
							var count_name=i + '_count';
							if (data[count_name] !== undefined) {
								switch(my_client_filter.operation[i]) {
								case 'le':
									if (data[count_name] > my_client_filter.threshold[i]) {
										threshold_check = false;
									}
									break;
								case 'lt':
									if (data[count_name] >= my_client_filter.threshold[i]) {
										threshold_check = false;
									}
									break;
								case 'gt':
									if (data[count_name] <= my_client_filter.threshold[i]) {
										threshold_check = false;
									}
									break;
								case 'ge':
									if (data[count_name] < my_client_filter.threshold[i]) {
										threshold_check = false;
									}
									break;
								case 'eq':
									if (data[count_name] != my_client_filter.threshold[i]) {
										threshold_check = false;
									}
									break;
								case 'ne':
									if (data[count_name] == my_client_filter.threshold[i]) {
										threshold_check = false;
									}
									break;
								default:
									break;
								}
							}
							if (!threshold_check) {
								break;
							}
						}

						if(threshold_check){
							impression_count++;
							var logData = {
								id: my_client_filter.id,
								referrer: document.referrer,
								location: document.location.href,
								uu_id: galileo_cookie,
								filter_name: client_filter_name,
								impression_count: impression_count,
								staging: staging
							};

							var addflg = false;
							switch(my_client_filter.contents.creative_no) {
								case 3:
									addflg = false;

									var option = {
										page_rate: my_client_filter.display.start.scroll_height,
										slide_height: my_client_filter.display.start.slide_height,
										slide_in_speed: my_client_filter.display.start.slide_in_speed,
										slide_out_speed: my_client_filter.display.start.slide_out_speed,
										run_once: function() {
											impressionLog(logData);
										},
										before_open: function() {
										}
									};

									IMG_POPUP.startView(option);

									var contents = {
										off_image: my_client_filter.contents.off_image,
										on_image: my_client_filter.contents.on_image,
										alt: my_client_filter.contents.alt,
										link: my_client_filter.contents.link
									};

									IMG_POPUP.updateContents(contents);
									break;
								case 2:
									addflg = false;
									jQuery("#recoArea").addClass("recoDpN");
									RECO_VIEW.status = "off";

									var option = {
										page_rate: my_client_filter.display.start.scroll_height,
										run_once: function() {
											impressionLog(logData);
										},
										before_open: function() {
										}
									};
									RECO_VIEW.startRecoView(option);
									var cl = my_client_filter.contents.reco_center_left.html;
									var cr = my_client_filter.contents.reco_center_right.html;

									RECO_VIEW.updateContents(cl, cr);
									break;
								case 1:
								default:
									var mylink = my_client_filter.contents.text;
									addflg = jQuery.gritter.add({
										title: my_client_filter.contents.title,
										text: mylink,
										image: my_client_filter.contents.image,
										sticky: false,
										before_open: function(){
											var exclude_impression = (my_client_filter.display.start.exclude_impression !== undefined) ? my_client_filter.display.start.exclude_impression : 1;
											if($('.gritter-item-wrapper').length >= exclude_impression) {
												// Returning false prevents a new gritter from opening
												return false;
											}
										}
									});
									break;
							}
							document.cookie = '__pppsc=1; path=' + my_client_filter.location + ';';
							if (addflg !== false ) {
								impressionLog(logData);				
							}
							jQuery("#popup-suumocounter").bind("mousedown", function(){
								clickLog(logData);
							});
						}
					}
					
					function mainFunction(){
						//page bottom detect
						if (my_client_filter.display.start.any_scroll || my_client_filter.display.start.page_bottom){
							var bottom_flag = false;
							var scroll_flag = false;
							var auto_load_enabled = true;
							var scroll_rate = (my_client_filter.display.start.scroll_height !== undefined) ? my_client_filter.display.start.scroll_height : 50;
							jQuery(window).scroll(function () {
							
								if (my_client_filter.display.start.any_scroll && scroll_rate == 0){
									callServerFilter();
								}

								if(!auto_load_enabled){
									return;
								}
								var document_y = document.documentElement.scrollHeight || document.body.scrollHeight;
								var scroll_y = document.documentElement.scrollTop || document.body.scrollTop;

								var window_y = 0;
								var isSafari = (navigator.appVersion.toLowerCase().indexOf('safari')+1?1:0);
								var isOpera = (navigator.userAgent.toLowerCase().indexOf('opera')+1?1:0);
								if (isOpera) isIE = false;

								if (!isSafari && !isOpera) {
									window_y = document.documentElement.clientHeight || document.body.clientHeight || document.body.scrollHeight;
								} else {
									window_y = window.innerHeight;
								}

								var scroll_threshold = parseInt((document_y - window_y) * scroll_rate / 100);
								// 終端から戻った判定
								if(bottom_flag && scroll_y <= document_y  - (window_y + 1)){
									bottom_flag = false;
								}
								// 終端判定
								if (!bottom_flag && my_client_filter.display.start.page_bottom && scroll_y > document_y  - (window_y + 1) ) {
									callServerFilter();
									bottom_flag = true;
								}
								
								// 
								if(scroll_flag && scroll_y <= scroll_threshold){
									scroll_flag = false;
								}
								if(scroll_flag) {
									return;
								}

								if(my_client_filter.display.start.any_scroll && scroll_y > scroll_threshold){
									callServerFilter();
									scroll_flag = true;
								}
							});
						}else{
							callServerFilter();
						}
					}
					//Main
					mainFunction();
				}
			},
			error: function() {
			}
		});
	}
	});
});

function ieCheck(){
	var userAgent = window.navigator.userAgent.toLowerCase();
	var appVersion = window.navigator.appVersion.toLowerCase();
	if (userAgent.indexOf("msie") > -1) {
		if (appVersion.indexOf("msie 6.0") > -1) {
			return 6;
		}
		else if (appVersion.indexOf("msie 7.0") > -1) {
			return 7;
		}
		else if (appVersion.indexOf("msie 8.0") > -1) {
			return 8;
		}
		else if (appVersion.indexOf("msie 9.0") > -1) {
			return 9;
		}
	}
	return -1;
}


// JSON.stringify
var JSON;
if (!JSON) {
	JSON = {};
}

(function () {
	"use strict";

	function f(n) {
		return n < 10 ? '0' + n : n;
	}

	if (typeof Date.prototype.toJSON !== 'function') {
		Date.prototype.toJSON = function (key) {
			return isFinite(this.valueOf()) ?
				this.getUTCFullYear()	  + '-' +
				f(this.getUTCMonth() + 1) + '-' +
				f(this.getUTCDate())	  + 'T' +
				f(this.getUTCHours())	  + ':' +
				f(this.getUTCMinutes())	  + ':' +
				f(this.getUTCSeconds())	  + 'Z' : null;
		};

		String.prototype.toJSON		 =
			Number.prototype.toJSON	 =
			Boolean.prototype.toJSON = function (key) {
				return this.valueOf();
			};
	}

	var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
		escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
		gap,
		indent,
		meta = {	// table of character substitutions
			'\b': '\\b',
			'\t': '\\t',
			'\n': '\\n',
			'\f': '\\f',
			'\r': '\\r',
			'"' : '\\"',
			'\\': '\\\\'
		},
		rep;


	function quote(string) {
		escapable.lastIndex = 0;
		return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
			var c = meta[a];
			return typeof c === 'string' ? c :
				'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
		}) + '"' : '"' + string + '"';
	}

	function str(key, holder) {
		var i,			// The loop counter.
			k,			// The member key.
			v,			// The member value.
			length,
			mind = gap,
			partial,
			value = holder[key];
		if (value && typeof value === 'object' &&
				typeof value.toJSON === 'function') {
			value = value.toJSON(key);
		}

		if (typeof rep === 'function') {
			value = rep.call(holder, key, value);
		}

		switch (typeof value) {
		case 'string':
			return quote(value);
		case 'number':
			return isFinite(value) ? String(value) : 'null';
		case 'boolean':
		case 'null':
			return String(value);
		case 'object':
			if (!value) {
				return 'null';
			}
			gap += indent;
			partial = [];
			if (Object.prototype.toString.apply(value) === '[object Array]') {
				length = value.length;
				for (i = 0; i < length; i += 1) {
					partial[i] = str(i, value) || 'null';
				}
				v = partial.length === 0 ? '[]' : gap ?
					'[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
					'[' + partial.join(',') + ']';
				gap = mind;
				return v;
			}
			if (rep && typeof rep === 'object') {
				length = rep.length;
				for (i = 0; i < length; i += 1) {
					if (typeof rep[i] === 'string') {
						k = rep[i];
						v = str(k, value);
						if (v) {
							partial.push(quote(k) + (gap ? ': ' : ':') + v);
						}
					}
				}
			} else {
				for (k in value) {
					if (Object.prototype.hasOwnProperty.call(value, k)) {
						v = str(k, value);
						if (v) {
							partial.push(quote(k) + (gap ? ': ' : ':') + v);
						}
					}
				}
			}
			v = partial.length === 0 ? '{}' : gap ?
				'{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
				'{' + partial.join(',') + '}';
			gap = mind;
			return v;
		}
	}

	if (typeof JSON.stringify !== 'function') {
		JSON.stringify = function (value, replacer, space) {
			var i;
			gap = '';
			indent = '';

			if (typeof space === 'number') {
				for (i = 0; i < space; i += 1) {
					indent += ' ';
				}

			} else if (typeof space === 'string') {
				indent = space;
			}
			
			rep = replacer;
			if (replacer && typeof replacer !== 'function' &&
					(typeof replacer !== 'object' ||
					typeof replacer.length !== 'number')) {
				throw new Error('JSON.stringify');
			}

			return str('', {'': value});
		};
	}
}());

