﻿// Global Java Script Codes
// © 2009 www.edreamer.ir, All Rights Reserved.
// Contact me at www.edreamer.ir/contact.aspx for more information

/*-----------------------------------------------------------------------------------------------
    overlay functions
-----------------------------------------------------------------------------------------------*/

function showoverlay(dense)
{
    var arrayPageSize = getPageSize();
    
    if (document.getElementById("overlay") == null)
    {
        $("body").append("<div id='overlay'/>");
	}
    
    if (dense == 'dark'){$("#overlay").addClass("dark");}
    $("#overlay").height(arrayPageSize[1] + "px");
    $("#overlay").after("<div id='loading' />");
    $("#overlay").fadeIn('normal');
    $('#overlay').supersleight();
    
    centerelement("loading");
    $("#loading").supersleight();
    $("#loading").fadeIn('slow');
    
    window.onscroll = function()
    {
        arrayPageSize = getPageSize();
        $("#overlay").height(arrayPageSize[1] + "px");
        centerelement("loading");
    }
    
	window.onresize = function()
	{
	    arrayPageSize = getPageSize();
        $("#overlay").height(arrayPageSize[1] + "px");
        centerelement("loading");
	}
}

function hideoverlay()
{
    $("#loading").fadeOut('fast');
    $("#loading").remove();
    $("#overlay").fadeOut('fast');
    $("#overlay").remove();
    window.onscroll = "";
    window.onresize = "";
}

// Returns array with page width, height and window width, height 
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function getScrollingPosition()
{
	var position = [0, 0];
	if (typeof window.pageYOffset != 'undefined')
	{
		position = [window.pageXOffset,window.pageYOffset];
	}
	else if (typeof document.documentElement.scrollTop != 'undefined' && document.documentElement.scrollTop > 0 || document.documentElement.scrollLeft > 0)
	{
		position = [document.documentElement.scrollLeft,document.documentElement.scrollTop];
	}
	else if (typeof document.body.scrollTop != 'undefined')
	{
		position = [document.body.scrollLeft,document.body.scrollTop];
	}
	return position;
}

function getViewportSize()
{
	var size = [0, 0];
	if (typeof window.innerWidth != 'undefined')
	{
		size = [window.innerWidth,window.innerHeight];
	}
	else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0)
	{
		size = [document.documentElement.clientWidth,document.documentElement.clientHeight];
	}
	else
	{
		size = [document.getElementsByTagName('body')[0].clientWidth,document.getElementsByTagName('body')[0].clientHeight];
	}
	return size;
}

/*-----------------------------------------------------------------------------------------------
    dialog functions
-----------------------------------------------------------------------------------------------*/

function showdialog(content, type, title, width, height, icon, callback, modal)
{
//    if (typeof document.body.style.maxHeight === "undefined") //if IE 6
//    {
//        $("body","html").css({height: "100%", width: "100%"});
//        $("html").css("overflow","hidden");
//    }
    
    showoverlay("dark");

    // add dialog markup to the body of the document
    if (document.getElementById("dialogbox") == null)
    {
        $("body").append("<div id='dialogbox'/>");
	}
	else
	{
        closedialog(false);
        return false;
	}
    
    // seting up the dialog box
    $("#dialogbox").width(width);
    $("#dialogbox").height(height);
    
    // title
    if(title != '')
    {
        $("#dialogbox").append("<h3 id='dialogbox-title'>" + title + "</h3>");
    }
    
    centerelement("dialogbox");
    
    if (icon != null)
    {
        switch(icon)
        {
            case "confirm":
                $("#dialogbox-title").addClass("confirm");
                break;
                
            case "error":
                $("#dialogbox-title").addClass("error");
                break;
                
            case "warning":
                $("#dialogbox-title").addClass("warning");
                break;
                            
            case "loading":
                $("#dialogbox-title").addClass("loading");
                break;
        }
    }
    
    // contents
    switch(type)
    {
        case "url":
            $("#dialogbox").append("<div id='dialogbox-content'><iframe frameborder='0' hspace='0' src='" + content + "' title='Dialog' scrolling='auto' id='dialogboxframe' name='dialogboxframe" + Math.round(Math.random()*1000) + "' onload='self.parent.showiframecontent()' > </iframe></div>");
            break;
            
        case "inline":
            var str = parent.document.getElementById(content).innerHTML;
            $("#dialogbox").append("<div id='dialogbox-content'>" + str + "</div>");
	        break;
	        
	    case "message":
	        //var str = "<p>" + content + "</p><a class='dialogbox-ok' href='#'>تائید<br/><em>تایید عملیات و ادامه</em></a>";
	        var str = "<p>" + content + "</p>";
		    $("#dialogbox").append("<div id='dialogbox-content'>" + str + "</div>");
	        break;
	        
	    case "confirm":
	        if (callback == null)
	        {
	            var str = "<p>" + content + "</p><a class='dialogbox-ok' >بلی<br/><em>تایید عملیات و ادامه</em></a>" +
	            "<a class='dialogbox-cancel' href='#'>خیر<br/><em>انصراف و بازگشت</em></a>";
	        }
	        else
	        {
	            var str = "<p>" + content + "</p><a class='dialogbox-callback' href=\"" + callback + "; closedialog();\">بلی<br/><em>تایید عملیات و ادامه</em></a>" +
	            "<a class='dialogbox-cancel' href='#'>خیر<br/><em>انصراف و بازگشت</em></a>";
	        }
	        
	        $("#dialogbox").append("<div id='dialogbox-content'>" + str + "</div>");
	        break;
    }
    
    // register dialog event handlers
    if (modal != true)
    {
        //$('#dialogbox').prepend("<span class='dialogbox-cancel' title='Close'/>");
        
        $('#overlay').click(function()
        {
            closedialog(false);
            return false;
        });
        
        // ESC key
        document.onkeyup = function(e)
        { 	
            if (e == null) // ie
            {
                keycode = event.keyCode;
            }
            else // mozilla
            {
                keycode = e.which;
            }
            
            if(keycode == 27) // close
            {
                closedialog(false);
                return false;
            }
        }
    }
    
    $('.dialogbox-cancel').click(function()
    {
        closedialog(false);
        return false;
    });
    
    $('.dialogbox-ok').click(function()
    {
        closedialog(true);
        return false;
    });

    window.onscroll = function() {centerelement("dialogbox");}
	window.onresize = function() {centerelement("dialogbox");}
    
    if (type != 'url'){$("#loading").fadeOut('fast');}
    
    // display dialog
    $("#dialogbox").fadeIn('normal');
}

function centerelement(elementid)
{
    var element = document.getElementById(elementid);
    
    if (typeof document.body.style.maxHeight === "undefined") //if IE 6
    { 
        var scrollingPosition = getScrollingPosition();
        var viewportSize = getViewportSize();
        
        $(element).css("left",scrollingPosition[0] + parseInt(viewportSize[0] / 2) - parseInt($(element).width() / 2) + "px");
        $(element).css("top",scrollingPosition[1] + parseInt(viewportSize[1] / 2) - parseInt($(element).height() / 2) + "px");
    }
    else
    {
        $(element).css({marginLeft: '-' + parseInt(($(element).width() / 2),10) + 'px', width: $(element).width() + 'px'});
        $(element).css({marginTop: '-' + parseInt(($(element).height() / 2),10) + 'px'});
    }
}

function closedialog(answer)
{
    if (typeof document.body.style.maxHeight === "undefined") //if IE 6
    { 
        $("body","html").css({height: "auto", width: "auto"});
        $("html").css("overflow","");
    }
    
    $("#dialogbox").fadeOut('normal');
    $('#dialogbox').remove();
    
    $('#overlay').unbind("click");
    hideoverlay();
    
    window.onscroll = "";
    window.onresize = "";
	document.onkeyup = "";
    
    //alert(answer);
    return answer;
}

function showiframecontent()
{
    $("#loading").fadeOut('fast');
    $("#dialogboxframe").fadeIn('fast');//$("#dialogboxframe").css({display:"block"});
}

/*-----------------------------------------------------------------------------------------------
    other functions
-----------------------------------------------------------------------------------------------*/

//jQuery.browser report version wrongly
//alert(BrowserDetect.browser);
//alert(BrowserDetect.version);
//alert(BrowserDetect.OS);

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

// comment deletion confirmation
function confirm(callback)
{
    showdialog('آیا از حذف نظر خود مطمئن هستید؟', 'confirm', 'تائید کنید', 300, 150, 'confirm', callback);
    return false;
}

// account deletion confirmation
function confirmaccount(callback)
{
    showdialog('این عملیات قابل بازگشت نیست. آیا از حذف حساب کاربری خود مطمئن هستید؟', 'confirm', 'حذف حساب کاربری', 300, 150, 'warning', callback);
    return false;
}

// slide down the design tip
function showdesigntip()
{
    $('#designtip').supersleight();
    $('#designtip-closer').supersleight();
    $('.narrow #designtip').slideDown('slow').next().slideDown('slow');
}

function subscribetonewsletter()
{
    var email = "";
    
    if (window.document.getElementById('newsletteremail') != null) {
        var email = window.document.getElementById('newsletteremail').value;
        window.document.getElementById('newsletteremail').value = "";
    }
    
    showdialog('/NewsletterRegister.aspx?Email=' + email, 'url', 'عضویت در رویاگر', 360, 400);
 }

function hireme()
{
    $('a.hireme').supersleight();
    $('a.hireme').fadeIn("slow");
    return false;
}

/*-----------------------------------------------------------------------------------------------
    event handlers and onload
-----------------------------------------------------------------------------------------------*/

$(document).ready(function()
    {
        // find a elements that have an "external link" class
        $('.externallink').click(function()
        {
            window.open(this.href);
            return false;
        });
        //$('a[@rel$='external']').click(function()
        //{
        //    this.target = "_blank";
        //});
        
        // smooth page scrolling
        $('a[href*=#]').click(function()
        {
            if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname && this.hash.length != 0)
            {
                var $target = $(this.hash);
                $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
                if ($target.length)
                {
                    var targetOffset = $target.offset().top;
                    $('html,body').animate({scrollTop: targetOffset}, 1000);
                    return false;
                }
            }
        });
        
        // antibotimage
        $('#antibotimage').click(function()
        {
            $(this).fadeOut('fast').attr("src","code.aspx?" + Math.round(Math.random()*10000)).fadeIn('fast');
            return false;
        });
        
        // print page
        $('.print').click(function()
        {
            parent.print();
            return false;
        });
        
        // previous page
        $('.previous').click(function()
        {
            history.back();
            return false;
        });        
        
        // latest work more info
        $('#latestwork > ul > li > p').hover(function()
        {
            $(this).next().slideDown();
            return false;
        },
        function ()
        {
            $(this).next().slideUp();
            return false;
        });
        
        // most visited post more info
        $('#popular ul li a').hover(function()
            {
                $(this).find('em').fadeIn();
                return false;
            },
            function ()
            {
                $(this).find('em').slideUp();
                return false;
            }
        );
        
        // search
        $('.searchbutton').click(function()
        {
            if
            (($('#ctl00_SecondaryContentPlaceHolder_SecondaryContents_Search_searchTextBox').attr('value')) == "" ||
                ($('#ctl00_SidebarContentPlaceHolder_SecondaryContents_Search_searchTextBox').attr('value')) == "")
            {
                showdialog('لطفاً عبارتی را برای جستجو وارد کنید!', 'message', 'جستجو', 250, 25);
                //$('#ctl00_SecondaryContentPlaceHolder_SecondaryContents_Search_searchTextBox')[0].focus();
                return false;
            }
            else
            {
                return true;
            }
        });
        
        
        // display all links
        $('.alllinks').click(function()
        {
            showdialog('/SiteLinksDialog.aspx', 'url', 'لینکهای تائید شده', 617, 500);
            return false;
        });
        
        // register newsletter
        $('.registerbutton').click(function()
            {
                subscribetonewsletter();
                return false;
            });
            
            
        // accessibility options
        $('.accessbutton').click(function()
        {
            $("body").append("<div id='accessibility' style='display:none;'>" +
            "<p>با وجود ناسازگاری بین مرورگرهای مختلف تمام تلاشم را انجام دادم که سایت رویاگر کاملاً مطابق با قواعد دسترسی پذیری طراحی گردد. از مهمترین خصوصیاتی که در این زمینه برای بیندگان سایت فراهم شده می توان به امکان مرور کامل سایت توسط صفحه کلید، تعریف کلیدهای دسترسی برای مهمترین بخشهای سایت، کنترل ترتیب حرکت کاربر با کلید TAB و بکارگیری رنگ آمیزی با تضاد مناسب اشاره کرد.</p>" +
            "<p>در قسمتهای مختلف سایت، میانبرهای دسترسی با زیرخط و یا در Tooltip کنترل معرفی شده اند. در مرورگر Internet Explorer، کلیدهای دسترسی با فشردن <code>Alt</code> و در Firefox با ترکیب کلیدی <code>Alt+Shift</code> قابل استفاده هستند. اگرچه قشر مخاطب رویاگر، عموم مردم نیستند، اما برای موارد خاص در این قسمت امکان سویچ به نسخه کنتراست بالای سایت فراهم شده است.</p>" +
            "<a title='کنتراست بالای متن' onclick='chooseStyle(\"High Contrast\", 60); closedialog();' href='#'>سوییچ به نسخه کنتراست بالای سایت<br/><em>تنظیم  عناصر بصری سایت برای آسانترین حالت مطالعه و دسترسی.</em></a>" +
            "<a title='کنتراست عادی متن' onclick='chooseStyle(\"none\", 60); closedialog();' href='#'>بازگشت به حالت عادی<br/><em>استفاده از تنظیمات پیش فرض عناصر بصری سایت.</em></a>" +
            "</div>" );
            showdialog('accessibility', 'inline', 'دسترسی پذیری', 500, 350);
            
            $("#accessibility").remove();
            return false;
            });
            
        
        // no ie6 upgrade link
        $('.noie').click(function()
        {
            $("body").append("<div id='noie6' style='display:none;'>" +
            "<p>شما از نسخه قدیمی مرورگر Internet Explorer استفاده می کنید. چون این مرورگر در August 2001 تولید شد، قابلیت پشتیبانی بسیاری از تکنولوژی های کنونی وب را دارا نیست و با استفاده از این مرورگر عملاً خودتان را از این امکانات محروم می کنید. همینطور بخاطر مشکلات امنیتی بسیار این مرورگر و عدم پشتیبانی از استانداردهای وب، ارتقاء به یک مرورگر مدرن را برای نمایش بهتر و سریعتر صفحات وب و حفظ حریم شخصیتان به شما توصیه می کنم.</p>" +
            "<p>جایگزین های زیادی برای ارتقای مرورگر شما وجود دارند. همه مرورگرهای پرطرفدار رایگان هستند و با آسانی نصب می شوند. </p>" +
            "<a title='Microsoft Internet Explorer' class='externallink tooltip' href='http://www.microsoft.com/windows/downloads/ie/getitnow.mspx'>Microsoft Internet Explorer<br/><em>امنیت و رابط کاربری اصلاح شده، امکان مرور بر پایه برگ صفحه، مرور محرمانه وب و بیشترین هماهنگی با سیستم عامل.</em></a>" +
            "<a title='Mozilla Firefox' class='externallink tooltip' href='http://www.getfirefox.com/'>Mozilla Firefox<br/><em>امنیت، امکان پیشرفته سازی به کمک افزونه ها، مرور بر پایه برگ صفحه، پشتیبانی جدیدترین تکنولوژی ها، مرور محرمانه وب و سرعت بالا.</em></a>" +
            "<a title='Opera' class='externallink tooltip' href='http://www.opera.com/download/'>Opera<br/><em>امنیت، امکانات بسیار با قابلیت تنظیم، مرور بر پایه برگ صفحه و سرعت بالا. مرورگر محبوب دستگاهای همراه.</em></a>" +
            "<a title='Apple Safari' class='externallink tooltip' href='http://www.apple.com/safari/download/'>Apple Safari<br/><em>امنیت، امکان مرور بر پایه برگ صفحه. مرورگری ازشرکت اپل.</em></a>" +
            "</div>" );
            showdialog('noie6', 'inline', 'دوست عزیز!', 500, 450);
            
            $("#noie6").remove();
            return false;
        });
        
        
        // Copyright!!
        $('.copyrightbutton').click(function()
        {
            $("body").append("<div id='copyrightquote' style='display:none;'>" +
            "<p>هیچ چیز اصیل نیست. از هر کجا که الهام را قوت می بخشد و تصور و خیالتان را تشدید می کند، بدزدید.</p>" +
            "<p>فیلم های قدیمی، جدید، موسیقی، کتاب ها، نقاشی ها و عکس ها، شعر ها، رویا ها، صحبت های اتفاقی، معماری ها، پل ها، علامت های نصب شده در خیابان، ‌درخت ها، ابر ها، چاله های آب و نور ها و سایه ها را حریصانه ببلعید. فقط چیز هایی را بدزدید که مستقیم با روحتان ارتباط برقرار می کند. اگر این کار را انجام دهید، اثرتان (همان که دزدیده اید) صحیح و معتبر خواهد بود.</p>" +
            "<p>اعتبار و صحت فوق العاده گرانبهاست. اصالتی وجود ندارد.</p>" +
            "<p>و خود را برای مخفی کردن آن سرقت به زحمت میاندازید - اگر چنین احساسی دارید، آن را جشن بگیرید. در هر صورت، همیشه به خاطر داشته باشید که Jean Luc Godard گفته است:</p>" +
            "<p><code><strong>&rdquo;مهم نیست که چیزی را از کجا آورده اید، مهم این است که آن را به کجا می برید.&ldquo;</strong></code></p>" +
            "<p>&mdash;	Jim Jarmusch</p>" +
            "</div>" );
            showdialog('copyrightquote', 'inline', '!?Copyright', 500, 375);
            
            $("#copyrightquote").remove();
            return false;
        });
        
        // fix IE6 PNG problem
        // $('#wrapper').supersleight();
        
        
        // user login trigger
        $('#trigger').toggle(function()
            {
                $('#login').slideDown('fast').addClass("up tooltip");
                $('#trigger').removeClass().addClass("down tooltip")
                $('.hireme').fadeOut('slow');
                return false;
            },
            function() {
                $('#login').slideUp('slow');
                $('#trigger').removeClass().addClass("up tooltip")
                $('.hireme').fadeIn('slow');
                return false;
            });
            
        // profile accordion
        $(".accordion div.container").hide();
        
        // opening default one
        //$(".accordion h3").eq(0).addClass("active");
        //$(".accordion div.container").eq(0).show();
        
        $(".accordion h3").click(function()
            {
                $(this).next("div.container").slideToggle("normal").siblings("div.container:visible").slideUp("slow");
                $(this).toggleClass("active");
                $(this).siblings("h3").removeClass("active");
            });
            
        // design tip hover effect
        $('.narrow #designtip').hover(function()
        {
            $(this).find('ul').slideDown('fast');
            return false;
        },
        function ()
        {
            $(this).find('ul').slideUp();
            return false;
        });            
            
        //hideoverlay();
        showdesigntip();
        hireme();
    });