﻿// Rasekhoon page scripts

$(function () {
	$("#loginpanel").hide();
	$("#themepanel").hide();

	_ref = document.referrer;
	if ($.trim(_ref) != "" && _ref.indexOf("google") != -1) {

		_spos = _ref.indexOf("q=");
		mystr = _ref.substring(_spos + 2, _ref.length);

		_q = mystr.substring(0, mystr.indexOf("&"));
		showSearchDialog(_q);
	}

	CurrentPanels_array = new Array();
	AvailablePanles_array = new Array();

	try {
		if (DefaultPage) {
			$("#patch").click(function () {
				if ($('#setting').css('top') == '0px') {
					$('#setting').animate({ top: '-85px' }, 'fast', 'swing');
				}
				else {
					$('#setting').animate({ top: '0px' }, 'slow', 'swing');
					$("#loginpanel").animate({ bottom: '-70px' }, 'fast');
				}
			});
			$("#patch").css('background-image', 'url(/_img/setting_patch.png)');
			$("#patch").attr("title", "تنظیمات صفحه");
			setTimeout(function () {
				$("#suggestion").animate({ top: '-10px' }, 'fast');
			}, 3000);
		}
	}
	catch (e) {
		$("#patch").click(function () {
			$.cookie('ew-position', null);
			location.reload();
		});
		var CookieValue = $.cookie('ew-position');
		if (CookieValue != "" && CookieValue != null) {
			CookieValue = replaceAll(CookieValue, "p91", "");
			CookieValue = replaceAll(CookieValue, ",,", ",");
			CookieValue = replaceAll(CookieValue, "palceleft=", "palceleft=p91,");
			$.cookie('ew-position', CookieValue);
		}
		$("#patch").css('background-image', 'url(/_img/setting_reset.png)');
		$("#patch").attr("title", "تنظیمات پیش فرض صفحه");
	}


	$("#patch").animate({ "opacity": "show" }, "slow");


	$("#setting-reset").click(function () {
		$("#patch").click();
		$.cookie("ew-position", null);
		$.cookie("Rasekhoon_Theme", null);
		location.reload();
	});


	$("#setting-save").click(function () {

		var panels = $('#sections input');
		var placeright = "placeright=p20,p27,p30,";
		var placeleft = "placeleft=p91,";
		var places = null;
		if (CurrentPanels_array.length > 0) {
			for (var i = 0; i < panels.length; i++) {
				var myPanle = $(panels[i]).attr('name');
				if (myPanle == "p91" || myPanle == "p20" || myPanle == "p27" || myPanle == "p30")
					continue;

				if ($(panels[i]).attr('checked')) {
					if ($(panels[i]).val() == "0") {
						placeleft += $(panels[i]).attr('name') + ",";
					}
					else {
						placeright += $(panels[i]).attr('name') + ",";
					}
				}
			}

			placeleft = placeleft.substring(0, placeleft.length - 1);
			placeright = placeright.substring(0, placeright.length - 1);

			places = placeright + "|" + placeleft;
		}

		$("#patch").click();
		$.cookie('ew-position', places);
		window.location = "/?.rand=" + Math.random();
	});

	$("#searchBtn").click(function () {
		var section = $('#searchInput').attr('section');
		doSearch(section);
	});


	$("#login").click(function () {
		$("#loginpanel").show();
		if ($('#loginpanel').css('bottom') == '-70px') {
			$("#loginpanel").animate({ bottom: '26px' }, 'slow', 'swing', function () { $("#login-username").focus(); });
			$("#themepanel").animate({ bottom: '-35px' }, 'fast', function () { $("#themepanel").hide() });
			$('#setting').animate({ top: '-85px' }, 'fast');
		}
		else {
			$("#loginpanel").animate({ bottom: '-70px' }, 'slow', function () { $("#loginpanel").hide() });
		}
	});

	$("#theme").click(function () {
		$("#themepanel").show();
		if ($('#themepanel').css('bottom') == '-35px') {
			$("#themepanel").animate({ bottom: '10px' }, 'slow', 'swing');
			$("#loginpanel").animate({ bottom: '-70px' }, 'fast', function () { $("#loginpanel").hide() });
		}
		else {
			$("#themepanel").animate({ bottom: '-35px' }, 'slow', function () { $("#themepanel").hide() });
		}
	});

	$("#theme-green").click(function () {
		var obj = new Object();
		obj.name = "green";
		changeTheme(obj);
	});

	$("#theme-blue").click(function () {
		var obj = new Object();
		obj.name = "blue";
		changeTheme(obj);
	});

	$("#theme-gray").click(function () {
		var obj = new Object();
		obj.name = "gray";
		changeTheme(obj);
	});

	$("#theme-violet").click(function () {
		var obj = new Object();
		obj.name = "violet";
		changeTheme(obj);
	});


	$("#bookmark").click(function () {
		bookmark("http://rasekhoon.net", "راسخون - یار همیشه همراه");
	});

	$("#sug").click(function () {
		if ($("#suggestion").css('top') == '-110px') {
			$("#suggestion").animate({ top: '-10px' }, 'fast');
		}
		else {
			$("#suggestion").animate({ top: '-110px' }, 'fast');
		}

	});

	// jCarouselLite script
	$("#news").jCarouselLite({
		vertical: true,
		hoverPause: true,
		visible: 1,
		auto: 5000,
		speed: 500
	});

	// EasyWidgets Scripts
	$.fn.EasyWidgets({
		effects: {
			effectDuration: 300,
			widgetShow: 'slide',
			widgetHide: 'slide',
			widgetClose: 'slide',
			widgetExtend: 'slide',
			widgetCollapse: 'slide',
			widgetOpenEdit: 'slide',
			widgetCloseEdit: 'slide',
			widgetCancelEdit: 'slide'
		}
		,
		callbacks: {
			onClose: function (link, widget) {
				alert('Close the panel: ' + widget.attr('id'))
			}
		}

	});

	$(".more").click(function (e) {
		setCommentRate(this.id, 1);
	});

	$(".less").click(function (e) {
		setCommentRate(this.id, -1);
	});

	$('.window #close').click(function (e) {
		e.preventDefault();
		$('#mask').hide();
		$('#box .window').hide();
	});

	$('#mask').click(function () {
		$(this).hide();
		$('#box .window').hide();
	});

	$(".Astar").mouseenter(function (e) {
		for (var i = 1; i <= 5; i++) {
			var x = (i * 18) + 53;
			var str = "-" + x + "px 0px";
			$("#Arate" + i).css("backgroundPosition", str);
		}

		var star = parseInt(this.title);
		for (var i = 1; i <= star; i++) {
			var x = (i * 18) + 53;
			var str = "-" + x + "px 30px";
			$("#Arate" + i).css("backgroundPosition", str);
		}
	});

	$(".Astar").mouseleave(function (e) {
		for (var i = 1; i <= 5; i++) {
			var x = (i * 18) + 53;
			var str = "-" + x + "px 0px";
			$("#Arate" + i).css("backgroundPosition", str);
		}
	});

	$(".Astar").click(function (e) {
		var star = parseInt(this.title);
		DoContentRate(star);
	});


	setting_pre();

});


function setCommentRate(cid, rate)
{
	var cid = cid.substr(2, cid.length);

	section = $("#cr" + cid + " span").attr('section');
	if (section == undefined)
		section = $("#cr" + cid + " span").attr('xid');

	if ($.cookie(section + cid) == null)
	{
		$.cookie(section + cid, "1", { expires: 100, path: '/' });
		$.ajax({
			url: "/_ajaxapi/comment.aspx?action=rate&section=" + section + "&cid=" + cid + "&rate=" + rate,
			success: function (data) {
				if (data == -1)
					alert("کاربر گرامی رای شما برای این نظر، قبلا ثبت شده است.");
				else
					$("#cr" + cid + " span").html(data);
			}
		});
	}
	else
	{
		alert("کاربر گرامی رای شما برای این نظر، قبلا ثبت شده است");
	}
}

function DoContentRate(Rate) {
	var Rate = Rate;

	if ($.cookie(Section + "_" + RecordID) != null) {
		alert("کاربر گرامی رای شما قبلا ثبت شده است.");
		$("#Aloading").hide("fast");
		return;
	}
	else {
		$.cookie(Section + "_" + RecordID, "1");
	}

	$("#Aloading").show("fast");

	$.ajax({
		url: "/_ajaxapi/rate.aspx?section=" + Section + "&RecordID=" + RecordID + "&Rate=" + Rate,
		success: function (data) {

			if (data.toString() != "-1") {

				SetContentRate(data);

				var RateCount = parseInt($("#Div_RateCount").html());
				$("#Div_RateCount").html(RateCount + 1);
				$("#Aloading").hide("fast");
			}
			else {
				alert("کاربر گرامی شما بیش از یکبار نمی توانید به این مطلب رای دهید.");
				$("#Aloading").hide("fast");
				$.cookie(Section + "_" + RecordID, null);
			}

		},
		error: function (data) {
			alert("رای دهی با مشکل مواجه شد. لطفا دوباره سعی کنید.");
			$.cookie(Section + "_" + RecordID, null);
			$("#Aloading").hide("fast");
		}
	});
}

function SetContentRate(RecordRate) {
	for (var i = 1; i <= 5; i++) {
		if (i <= RecordRate)
			$("#Arate" + i).css("backgroundImage", "url(/_img/articletools.png)");
		else
			$("#Arate" + i).css("backgroundImage", "url(/_img/articletools_org.png)");
	}
};


//function showSearchDialog(_q) {
//	var maskHeight = $(document).height();
//	var maskWidth = $(window).width();
//	var section = $('#searchInput').attr('section');

//	$('#mask').css({ 'width': maskWidth, 'height': maskHeight });

//	$('#mask').fadeIn(500);
//	$('#mask').fadeTo("slow", 0.8);

//	var winH = $(window).height();
//	var winW = $(window).width();

//	id = "#searchDialog";

//	$(id).css("top", winH / 2 - $(id).height() / 2);
//	$(id).css("left", winW / 2 - $(id).width() / 2);
//	_q = decodeURI(_q);

//	$(id).html($(id).html() + " شما با جستجوی عبارت <b> \" " + _q + " \" </b> به پایگاه راسخون هدایت شده اید.<br />");
//	$(id).html($(id).html() + "چنانچه مایل باشید، می توانید جستجوی دقیقتری از این عبارت در بخش جستجوی راسخون داشته باشید. فقط کافیست بر روی عبارت زیر کلیک کنید.<br /><br />");
//	$(id).html($(id).html() + "<a href='/search/?Page=1&Words=" + escape(_q) + "&SWhere=" + section + "&SData=subjects&SType=OR' style='text-decoration:none'><b>" + _q + "</b></a>");

//	$(id).fadeIn(1000);
//};

function changeTheme(obj)
{
	$.cookie("Rasekhoon_Theme", obj.name, {path:"/", expires:365});
	$(".themeStyle").attr("href", "/_doc/"+obj.name+".css");
	//ribbonBack
	$("#logo img").attr("src", "/_img/header_logo_"+obj.name+".png");
	$("#themepanel").animate({bottom:'-35px'},'slow',function(){$("#themepanel").hide()});
}

function setting_pre()
{
	var positions = $.cookie('ew-position');
	if( (positions != null) )
	{
	  
      // Get the widgets places IDs and widgets IDs
      var places = positions.split("|");
      var totalPlaces = places.length;
      for(var i = 0; i < totalPlaces; i++){
        // Every part contain a place ID and possible widgets IDs
        var place = places[i].split('=');
        // Validate (more or less) the format of the part that must
        // contain two element: A place ID and one or more widgets IDs
        if(place.length == 2){
          // Subpart one: the place ID
          var placeSel = '#'+place[0];
          // Subpart two: one or more widgets IDs
          var widgets = place[1].split(',');
          var totalWidgets = widgets.length;
          // Here we have a place and one or more widgets IDs
          for(var j = 0; j < totalWidgets; j++){
            if($.trim(widgets[j]) != ''){
              // So, append every widget in the appropiate place
              var widgetSel = ''+widgets[j];
			  //alert(widgetSel);
			  CurrentPanels_array.push(widgetSel);
              //$(widgetSel).appendTo(placeSel);
            }
          }
        }
      }
    }
	

	
	var panels = $('#sections input');
	
	if(CurrentPanels_array.length > 0)
	{
		for(var i=0; i<panels.length; i++)
		{
			AvailablePanles_array.push("#"+panels[i].name);
			if($.inArray(panels[i].name, CurrentPanels_array) != -1)
				$(panels[i]).attr('checked', true);
		}
	}
};

function suggestionAlerter(action)
{
	if(action == 'start')
	{
		SuggestionInterval = setInterval(function(){
			$("#sug").css('background-position', '(-182px 26px)');
			$("#sug").css('background-position', '(-182px 0px)');
			$("#sug").css('background-position', '(-182px 26px)');
			$("#sug").css('background-position', '(-182px 0px)');
		},2000);
	}
	else
	{
		$("#sug").css('background-position', '(-182px 0px)');
		SuggestionInterval = null;
	}
}


function bookmark(url,title)
{
	if (window.sidebar) {return window.sidebar.addPanel(title,url,"")}
	else if (window.external) {return window.external.AddFavorite(url,title)}
	else if (window.opera && window.print) {return true};
	return false;
};

function doSearch(section)
{
	if (section == "")
		var selectedSubject = "Article";
	else
		var selectedSubject = section;

	var searchLocation = "/search/";
	var _searchBox = $("#searchInput");
	window.location.href = searchLocation + "?Page=1&Words=" + escape(_searchBox.val()) + "&SWhere=" + selectedSubject + "&SData=allfields&SType=OR";
};

function isEnterPressed(e)
{
	var _char
	if(e && e.which)
	{
		e = e;
		_char = e.which; // NN4 specific code
	}
	else
	{
		e = event;
		_char = e.keyCode; // IE specific code
	}
	if(_char == 13) return true;   // Enter key is 13
	else return false;
};

function replaceAll(_str, _oldChar, _newChar)// :String;
{
	return _str.split(_oldChar).join(_newChar);
};


function OstanChange(OstanID) {

	var DL = document.getElementById("ShahrDL");
	clearOptions(DL);

	var optn = document.createElement("OPTION");
	optn.text = "لطفا منتظر بمانيد";
	optn.value = "-1";
	DL.options.add(optn);
	AjaxGetVal(OstanID, '', 1);
}
function OstanFill(CityStr) {
	if (CityStr == "")
		return;
	var DL = document.getElementById("ShahrDL");
	var ostanTXT = CityStr;
	clearOptions(DL);
	while (ostanTXT.length != 0) {
		var endL = ostanTXT.indexOf("&");
		var tmpit = ostanTXT.substr(0, endL);
		ostanTXT = ostanTXT.substr(endL + 1);

		var optn = document.createElement("OPTION");
		optn.text = tmpit.substr(tmpit.indexOf('#') + 1);
		optn.value = tmpit.substr(0, tmpit.indexOf('#'));
		DL.options.add(optn);
	}
	CityChange(document.getElementById("ShahrDL").value)
}
function CityChange(shahrid) {
	document.getElementById("CityTB").value = document.getElementById("ShahrDL").value;
}

/*
var objXMLHTTP = null;
var objXMLHTTPpop = null;
function AjaxGetVal(Myval, stat, MyType) {

	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
		objXMLHTTP = new XMLHttpRequest();
		objXMLHTTPpop = new XMLHttpRequest();
	}
	if (window.ActiveXObject) { // IE
		try {
			objXMLHTTP = new ActiveXObject("Msxml2.XMLHTTP");
			objXMLHTTPpop = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			try {
				objXMLHTTP = new ActiveXObject("Microsoft.XMLHTTP");
				objXMLHTTPpop = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e1) {
				objXMLHTTP = null;
				objXMLHTTPpop = null;
			}
		}
	}
	var strOutput;

	strOutput = 'Error';
	objXMLHTTP.open("GET", 'ajax.aspx?MyVal=' + Myval + '&MyDiv=' + stat + '&MyType=' + MyType);
	objXMLHTTP.onreadystatechange = AjacBack;
	objXMLHTTP.send(null);
}
function AjacBack() {
	var strout = "";
	if (objXMLHTTP.readyState == 4 && objXMLHTTP.status == 200) {
		strOutput = objXMLHTTP.responseText;
		OstanFill(strOutput);
	}
}
*/
function clearOptions(list) {
	var i;
	for (i = list.options.length - 1; i >= 0; i--) {
		list.remove(i);
	}
}
