var userLogged = 0;

$(document).ready(function(){
	//ana yüklemeler
	initAll();
	
	//user status
	if($("div.userInfo",'#mf_head').hasClass('loggedIn')){
		userLogged = 1;
	}
	
	//citySelect
	$("#dealCitySelect").change( function() {
		var cityName = $(this).val();
		if(/^([a-z]{1,15})$/.test(cityName)) {
			window.location.href="/sehir-firsatlari/"+cityName+"/gunun-firsati.html";
		} else {
			window.location.href="/sehir-firsatlari/istanbul/gunun-firsati.html";
		}
		//alert("/sehir-firsatlari/"+cityName+"/gunun-firsati.html");
		return false;
	});
	
 });


/*********************************************************
	B) - EXTERNAL JQUERY PLUGINS
*********************************************************/
/* B-1) - jQuery doOnce plugin - http://paulirish.com/2008/jquery-doonce-plugin-for-chaining-addicts/ */
	jQuery.fn.doOnce = function(func){
		this.length && func.apply(this);
		return this;
	};


/*********************************************************
	C) - GENEL DEGISKENLER
*********************************************************/
	var count_value = 0;


/*********************************************************
	D) -FONKSIYONLAR
*********************************************************/
/* D-1)  -  trim */
function jsTrim(s) {
	// http://doc.infosnel.nl/javascript_trim.html
	var l=0; var r=s.length -1;
	while(l < s.length && s[l] == ' ') {	l++; }
	while(r > l && s[r] == ' ') {	r-=1;	}
	return s.substring(l, r+1);
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

/* D-2) - initialize */
function initAll() {
	//jsMain işlemlerini başlatıyoruz
	//initialize();

	//sayfa içi sayac -- sistemsel tetikleme işlemler
	initializeCounter();

	//bulundugu sayfada tetiklenecek bi fonksiyon varsa onu tetikliyoruz
	if(typeof (innerJS_initAll) == "function") {
		innerJS_initAll();
	}
}

/* - D-3) sayfa içi sayac -- sistemsel tetikleme işlemleri
	- kaldırdım. tek bir fonk için degmez. ilerde gerekiyorsa eklenir.
	function initialize() {
			initializeCounter();
	}
*/

/* - D-4) sayfa içi sayac -- sistemsel arka plan işlerini atıyor */
function initializeCounter() {
	if(count_value==0 || count_value>60) {
		count_value=0;
	}
	if(count_value > 0) {
		if(count_value==60){
			markPeriod60Sec();
		}
	}
	count_value += 1;
	return setTimeout("initializeCounter();",1000);
}

/* - D-5) her 60 saniyede bir yapılan işler */
function markPeriod60Sec() {
 	//alert("1 dakika");
}

/* - D-6) test amaçlı */
function jsTestMe(){
	alert("ok");
}

/* - D-7) genel kontroller */
function jsCheckValue(myType,myValue) {
	switch(myType){
		case 'mail':
			myRegexPattern =/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-]+)+$/;
		break;
		case 'nick':
			myRegexPattern = /^([a-zA-Z0-9_]){2,16}$/;
		break;
		case 'pass':
			myRegexPattern = /^([a-zA-Z0-9_]){4,16}$/;
		break;
		case 'safePrint':
			myRegexPattern = /^([a-zA-Z0-9üÜşŞğĞiİıIçÇöÖ&_ \-]+)$/;
		break;
		case 'safePrintEntry':
			myRegexPattern = /^([a-zA-Z0-9üÜşŞğĞiİıIçÇöÖ&_\s\S\-]+)$/;
		break;
		case 'hash':
			myRegexPattern = /^([a-zA-Z0-9_]){2,16}$/;
		break;
		case 'integer':
			myRegexPattern = /^([0-9]){1,12}$/;
		break;
		default:
			return false;
		break;
	}
	if(myRegexPattern.test(myValue)){
		return true;
	}
	return false;
}

/* - D-8) - genel replacement */
function jsSafePrint(myType,myValue) {
	myRegexPattern = '';
	myValue = jsTrim(myValue);
	if(myValue.length<1) {
		return "jsSafePrint-Err-jsReplaceError";
	}
	switch(myType) {
		case 'file_name':
		case 'url_type':
			myRegexPattern = /[^a-z0-9\-]/gi;
		break;
		default:
			return 'jsSafePrint-Err-UnmatchedCase';
		break;
	}
	return myValue.replace(myRegexPattern,'-');
}

/* - D-9) - tr2en */
function jsTr2En(myValue) {
	if(myValue.length < 1) {
		return "";
	}
	var searchArr = new Array('ı','İ','ğ','Ğ','ü','Ü','ş','Ş','ö','Ö','ç','Ç');
	var replaceArr = new Array('i','i','g','G','u','U','s','S','o','O','c','C');
	for (var i=0; i<searchArr.length; i++) {
		var sRegExInput = new RegExp(searchArr[i], "g");
		myValue = myValue.replace(sRegExInput, replaceArr[i]);
	}
  return myValue;
}

/* - D-10) - setCookie*/
	function Set_Cookie(name,value,expires,path,domain,secure) {
		alert("Set_cookie called 183"); return false;
		// set time, it's in milliseconds - http://techpatterns.com/downloads/javascript_cookies.php
		var today = new Date();
		today.setTime( today.getTime() );
		/* 
		if the expires variable is set, make the correct
		expires time, the current script below will set
		it for x number of days, to make it for hours,
		delete * 24, for minutes, delete * 60 * 24
		*/
		if(expires){
			//expires = expires * 1000 * 60 * 60 * 24;
			expires = expires * 1000* 60* 60;	//saat 
		} else {
			expires = 0;
		}
		
		//root domaini bulalım  root_domain rootDomain
		var url = document.location.toString() ; //url
		var root_url = url.match(/:\/\/(www\.)?(.[^\/:]+)/)[2];
		domain = root_url ; 
		
		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" : "" );
	}
	function Get_Cookie( check_name ) {
		alert("get_cookie called 213"); return false;
		// first we'll split this cookie up into name/value pairs
		// note: document.cookie only returns name=value, not the other components
		var a_all_cookies = document.cookie.split( ';' );
		var a_temp_cookie = '';
		var cookie_name = '';
		var cookie_value = '';
		var b_cookie_found = false; // set boolean t/f default f

		for ( i = 0; i < a_all_cookies.length; i++ ) {
			// now we'll split apart each name=value pair
			a_temp_cookie = a_all_cookies[i].split( '=' );


			// and trim left/right whitespace while we're at it
			cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

			// if the extracted name matches passed check_name
			if ( cookie_name == check_name ) {
				b_cookie_found = true;
				// we need to handle case where cookie has no value but exists (no = sign, that is):
				if ( a_temp_cookie.length > 1 ) {
					cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
				}
				// note that in cases where cookie is initialized but no value, null is returned
				return cookie_value;
				break;
			}
			a_temp_cookie = null;
			cookie_name = '';
		}
		if ( !b_cookie_found ) {
			return null;
		}
	}
	
	function setCookie(c_name,value,exdays) {
		alert("Set_cookie called 250"); return false;
		Set_Cookie(c_name,value,30,'/','','');
		return true;
		var exdate=new Date();
		var c_value = '';
		var c_expire_date = '';
		
		if(exdays > 0){
			exdate.setDate(exdate.getDate() + exdays);
			c_expire_date = "; expires="+exdate.toUTCString(); 
		} else {
			exdays='';
		}
		
		if(value != ''){
			c_value= escape(value);
		}
		//root domaini bulalım  root_domain rootDomain
		var url = document.location.toString() ; //url
		var root_url = url.match(/:\/\/(www\.)?(.[^\/:]+)/)[2];
		document.cookie = c_name+"="+c_value+"; "+c_expire_date+"; path=/; domain=."+root_url; 
	}

/* - D-11) - getCookie*/		
	function getCookie(c_name)	{
		alert("Set_cookie called 274"); return false;
		return Get_Cookie(c_name);
		
	var i,x,y,ARRcookies=document.cookie.split(";");
	for (i=0;i<ARRcookies.length;i++)
	{
	  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
	  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
	  x=x.replace(/^\s+|\s+$/g,"");
	  if (x==c_name)
	    {
	    return unescape(y);
	    }
	  }
	}	

	
	
	
	
	
//facebook için 
	/*http://www.permadi.com/blog/2011/02/facebook-authenticationlogin-process-in-popup-or-not/
	 * http://www.permadi.com/blog/2011/04/centering-facebook-oath-login-popup-dialog/
	 * http://stackoverflow.com/questions/5200864/how-to-position-facebook-popup-window
	 * function logMeIn()
	{
	  var paramsLocation=window.location.toString().indexOf('?');
	  var params="user_about_me,user_birthday,user_location,email";
	  if (paramsLocation!=0)
	    params=window.location.toString().slice(paramsLocation);
	  top.location = 'https://graph.facebook.com/oauth/authorize?client_id=184347864978773&scope=publish_stream&redirect_uri=http://www.indirimucuz.com/';	  
	}*/
	function facebookLogin(response) {
		//return logMeIn();
		FB.login(function(response) {
			if (response.authResponse) {
				var fbu_id;
				var fbu_name;
				var fbu_gender;
				var fbu_link;	//profile link
				//var fbu_verified;
				var fbu_birthday;
				var fbu_email;
				var fbu_location;

				FB.api('/me', function(response) {
					var userInfo = document.getElementById('user-info');
					/*userInfo.innerHTML =
					'<img src="https://graph.facebook.com/'
					+ response.id + '/picture" style="margin-right:5px"/>'
					+ response.name;
					*/
					
					if(response.location) {
						fbu_location = response.location.name;
					}
					
					//ajax_call ile üyeyi register edelim + cookie set edelim -
					$.ajax({
					      url:		"/ajax_handleFacebookLogin",
					      global:	false,
					      type:		"POST",
					      data:		({	fbu_id:response.id,
										fbu_name:response.name,
										fbu_gender:response.gender,
										fbu_link:response.link,
										fbu_birthday:response.birthday,
										fbu_email: response.email,
										fbu_location: fbu_location
						      		}),
					      dataType:	"text",
					      async:	true,
					      beforeSend: function(msg){
					      },
					      success:	function(msg){
					    	  if(msg) {
					    		  alert("HATA: \n" + msg);
					    	  } else {
					    		  document.location.replace("/user/homepage.html");
					    	  }
					      }
					   }
					);
					//alert("id:"+fbu_id+"\nname:"+fbu_name+"\ngender:"+fbu_gender+"\nlink:"+fbu_link+"\nverified:"+fbu_verified+"\nbirthday:"+fbu_birthday+"\nemail:"+fbu_email+"\nlocation:"+fbu_location);
			    });
			    

			} else {
				//user cancelled login or did not grant authorization
				top.location.href='http://www.indirimucuz.com';
			}
        }, {scope:'user_about_me,user_birthday,user_location,email'});

	}

function goLink(str){
	var temp = str.split('|');
	temp[1] = parseInt(temp[1]);
	switch(temp[0]){
	case 'db':
		window.location.href="/dock/firsat-al/firsat-"+temp[1]+".html";
		break;
	case 'di':
		window.location.href="/dock/firsat/firsat-info-"+temp[1]+".html";
		break;
	case 'us':	//secimlerim
		if(temp[1]>0) {
			$.ajax({
		        url:      "/ajax_loadUserSettings",
		        global:   false,
		        type:     "POST",
		        dataType: "text",
		        async:    false,
		        beforeSend: function(msg){},
		        success:  function(msg){
		        	//alert(msg);
		        	window.location.href="/user/mysettings.html";
		        }
			});
		} else {
			window.location.href="/info/kayit-faydalari.html";
		}
		break;	
	default:
		break;
	}
	return true;
}
//if(typeof myVar !== 'undefined' || myVar) {}	
