﻿
/*-----------------------------------------------------------------------
                            UTILITIES FUNCTION
------------------------------------------------------------------------*/
function pagecount(total, pagesize){
    return parseInt(((total/pagesize) + 0.9999999),0);
}

function addOption(selectbox,text,value)
{
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);
}

//indicate hieght width of content
function CleanExt(str)
{
    return str;
}
function MaskOverPage(isShow)
{
    var div = document.getElementById("maskover");    
    
    if(isShow)
    {
        div.style.width = document.body.clientWidth + "px";
        div.style.height = screen.height - document.body.clientHeight + "px";
    }else
    {
        div.style.display='none';
    }
}

//style
function GetRandomStyle()
{
    var arr = new Array();
    var randomnumber=Math.floor(Math.random()*16)
    
    arr[arr.length]="progid:DXImageTransform.Microsoft.Iris(irisstyle='STAR' duration=1)";
    arr[arr.length]="progid:DXImageTransform.Microsoft.Iris(irisstyle='SQUARE' duration=1)";
    arr[arr.length]="progid:DXImageTransform.Microsoft.CheckerBoard(duration=1)";
    arr[arr.length]="progid:DXImageTransform.Microsoft.Blinds(Duration=1)";
    arr[arr.length]="progid:DXImageTransform.Microsoft.Fade(Duration=1)";
    arr[arr.length]="progid:DXImageTransform.Microsoft.Wheel(duration=1)";
    arr[arr.length]="progid:DXImageTransform.Microsoft.RandomDissolve()";
    arr[arr.length]="progid:DXImageTransform.Microsoft.Barn(orientation='vertical', motion='in')";
    arr[arr.length]="progid:DXImageTransform.Microsoft.Barn(orientation='vertical', motion='out')";
    arr[arr.length]="progid:DXImageTransform.Microsoft.Barn(orientation='horizontal', motion='in')";
    arr[arr.length]="progid:DXImageTransform.Microsoft.Barn(orientation='horizontal', motion='out')";
    arr[arr.length]="progid:DXImageTransform.Microsoft.Strips(motion='leftup')";
    arr[arr.length]="progid:DXImageTransform.Microsoft.Strips(motion='rightdown')";
    arr[arr.length]="progid:DXImageTransform.Microsoft.Strips(motion='rightup')";
    arr[arr.length]="progid:DXImageTransform.Microsoft.RandomBars(orientation='horizontal')";
    arr[arr.length]="progid:DXImageTransform.Microsoft.RandomBars(orientation='vertical')";
    
    return arr[randomnumber];
}

//browser detect
var is_ie = ( /msie/i.test(navigator.userAgent) &&
		   !/opera/i.test(navigator.userAgent) );
var is_ie5 = ( is_ie && /msie 5\.0/i.test(navigator.userAgent) );
var is_ie6 = ( is_ie && /msie 6\.0/i.test(navigator.userAgent) );
var is_ie7 = ( is_ie && /msie 7\.0/i.test(navigator.userAgent) );
/// detect Opera browser
var is_opera = /opera/i.test(navigator.userAgent);

//utility

function ShowMask()
{   document.getElementById("maskLayer").style.width = document.body.clientWidth + "px";
	document.getElementById("maskLayer").style.height = document.body.clientHeight + "px";
	document.getElementById("maskLayer").style.display  = "block";
}


function HoverThis(arg)
{    
   var src = $(arg).attr('src');
   while(src.indexOf("_h")!=-1)
   {
        src=src.replace("_h","");
   }
   var newpath = src.indexOf(".gif")!=-1?src.replace('.gif',"_h.gif"):src.replace('.png',"_h.png");
   $(arg).attr("src",newpath);
}

function UnHoverThis(arg)
{
   var src = $(arg).attr('src');
   var newpath = src.indexOf(".gif")!=-1?src.replace('_h.gif',".gif"):src.replace('_h.png',".png");
   $(arg).attr("src",newpath);
}

function tabThis(arg)
{
    $("#" + arg).parent().children().css({border:'1px solid #c4c4c4', cursor:'pointer'});
    //$("li [id^='li']").css({border:'1px solid #c4c4c4', cursor:'pointer'});
    $("#" + arg).css({border:'1px solid red', cursor:'default'});
    $("li.text_page_to_go").css({border:'none'});
}


    function getElementLeft(Elem) 
    {
    	
        var elem = Elem;
    //	if(document.getElementById) 
    //	{
    //		elem = document.getElementById(Elem);
    //	} 
    //	else if (document.all)
    //	{
    //		elem = document.all[Elem];
    //	}
        
	    xPos = elem.offsetLeft;
	    tempEl = elem.offsetParent;
	    while (tempEl != null) 
	    {
		    xPos += tempEl.offsetLeft;
  		    tempEl = tempEl.offsetParent;
	    }
	    return xPos;	
    }


    function getElementTop(Elem) 
    {	
        var elem = Elem;
    //	if(document.getElementById) 
    //	{	
    //		 elem = document.getElementById(Elem);
    //	} else if (document.all) 
    //	{
    //		 elem = document.all[Elem];
    //	}
	    yPos = elem.offsetTop;
	    tempEl = elem.offsetParent;
	    while (tempEl != null) 
	    {
		    yPos += tempEl.offsetTop;
  		    tempEl = tempEl.offsetParent;
	    }
	    return yPos;
    }

function myReplaceAll(str,src,des)
{
    while(str.indexOf(src)!=-1)
    {
        str = str.replace(src,des);
        //alert("ok");
    }
    return str;
}
//cursor
    function getPosition(e) {
    e = e || window.event;
    var cursor = {x:0, y:0};
    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    } 
    else {
        var de = document.documentElement;
        var b = document.body;
        cursor.x = e.clientX + 
            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        cursor.y = e.clientY + 
            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }
    return cursor;
}

//hien thi tab va an cac tab kia
    function showTab(arg)
    {
        var cont = arg.replace("tab","cont");
        $("#" + cont).parent().children().hide();
        $("#" + cont).show();
    }
    
//tab
function photo_active_tab(obj, num){
		var curentTab=obj.id; // id= tab8
		var curentContent=curentTab.replace("tab","cont"); //cont8
		var tabs=$('#' + curentTab).parent().children(); //#tab8 tab9
		var contents=$('#' + curentContent).parent().children(); //cont 8, cont 9		
		$(tabs).each( function(){								
				$(this).attr('class','');
		});		        
		$(contents).each( function(){								

				$(this).hide();
		});	
		$('#' + curentTab).addClass('active');
		$('#' + curentContent).show();			
}


function GetImageInfo(row)
{
    return "Tên hình:" + row.Caption + "<br/>Đăng bởi: " + row.UserID +  "<br/>Ngày đăng:" + dateFormat(row.UploadDate,"shortDate") + "<br/>Lượt truy cập:" + row.Clicked;
}

function rotateEffect(image_id,fopa){
        fopa += parseFloat('0.05');
        $(image_id).setOpacity(fopa);
        if(fopa<1)
        {
            window.setTimeout("rotateEffect('"+ image_id +"',"+ fopa +")",20);
        }
}

function toChar(str){
            str = str.Replace("%20", " ");
//            str = str.Replace("%28", "(");
//            str = str.Replace("%29", ")");
//            str = str.Replace("%5B", "[");
//            str = str.Replace("%5D", "]");
//            str = str.Replace("%7B", "{");
//            str = str.Replace("%7D", "}");
//            str = str.Replace("&amp;", "&");
//            str = str.Replace("&nbsp;", " ");
            return str;
            }

function charTo(str){
            str = str.Replace(" ", "%20");
            alert(str);
//            str = str.Replace("(", "%28");
//            str = str.Replace(")", "%29");
//            str = str.Replace("[", "%5B");
//            str = str.Replace("]", "%5D");
//            str = str.Replace("{", "%7B");
//            str = str.Replace("}", "%7D");
//            str = str.Replace("&", "&amp;");
//            str = str.Replace(" ", "&nbsp;");
            return str;
            }


/* ---------------------------------------------------
    Hàm kiểm tra kích thước ảnh và scale theo tỉ lệ
    Input: chiều rộng, chiều cao, hình nguồn
    Output: Hình đã scale theo kích thước Input 
------------------------------------------------------ */
function CheckImageSize(img, _width, _height)
{
//    if(img.width > img.height) // hinh nam ngang
//    {
//        if(img.width > _width)
//        {
//            img.width = _width;
//            img.height = img.height * _width / img.width;
//        }
//    }
//    else // hinh du'ng
//    {
//        if(img.height > _height)
//        {
//            img.hieght = _height;
//            img.width = img.width * _height/img.height
//        }
//    }
}
    
/* ---------------------------------------------------
    Hàm hiển thị khi đang load dữ liệu từ server
    Input: div nhận giá trị
    Output: div nhận giá trị
------------------------------------------------------ */
function isLoading(obj)
{
    if(typeof(obj) == "object")
    {
        obj.innerHTML = "<img src='Images/loading.gif' alt=''/>";
    }
    else
    {
        document.getElementById(obj).innerHTML ="<img src='Images/loading.gif' alt=''/>";
    }
}

/* ---------------------------------------------------
    Hàm hiển thị cửa sổ pupup Silver Light
    Input: albumid
    Output: cửa sổ popup
------------------------------------------------------ */
function Open_Window(arg)
    {
        window.open( "SilverLight.aspx?AlbumID="+arg, "SilverLight", "status = 1, height = 365, width = 555, resizable = 0" )
    }



/* ---------------------------------------------------
    Hàm hiển thị hay ẩn div cùng với dấu + or -
    Input: div nhận giá trị
    Output: div nhận giá trị
------------------------------------------------------ */
function ShowHideWithSign(div,tag)
{
    if(div.style.display=="none")
    {
        div.show();
        tag.innerHTML=" [ - ] ";
    }
    else
    {
        div.hide();
        tag.innerHTML=" [ + ] ";
    }
}


function GetPaging(rows,page,pagesize)
{
    var prePage="<li id='preview' onclick='javascript:PrevPage();'>" + AjaxFunction.getResourceKey("prePage").value +"</li>";
    var nextPage ="<li id='next' onclick='javascript:NextPage();'>"+AjaxFunction.getResourceKey("nextPage").value +"</li>";
    var page=parseFloat(rows)/pagesize;
    if(page%pagesize!=0)
    {
        page=parseInt(++page);
    }
    else
    {
        page=parseInt(page^pagesize);
    }
    alert(page); return false;
}


function addEvent(elm, evType, fn, useCapture) {
	if (elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture);
		return true;
	}
	else if (elm.attachEvent) {
		var r = elm.attachEvent('on' + evType, fn);
		return r;
	}
	else {
		elm['on' + evType] = fn;
	}
}

/*getParent Node*/
function getParentNode(obj)
{
    if(obj!=null)
    {
        return document.getElementById(obj.id).parentNode;
    }
}

/*Clear form text*/
function ClearObj(obj)
{
    ojb.value="";
}

/*Check text input*/
function checkTextInput(obj)
{
    return obj!=null&&obj.value!="";
}

/*Using to set property of element display:none*/
function hideObj(obj)
{   
    if(obj!=null)
    {
        obj.style.display='none';
    }
}

/*Show Obj*/
function showObj(obj)
{   
    if(obj!=null)
    {
        obj.show();
    }
}

/*Using to toggle display of object indicate*/
function ShowHide(obj)
{
    if(obj.style.display=='none')
    {
        obj.style.display='block';
    }
    else
    {
        obj.style.display='none';
    }
}

/*Change text color*/
function changeTextColor(obj,color)
{
    if(obj!=null)
    {
        obj.style.color=color;
    }
}
/*changeBGcolor*/
function changeBGColor(obj,color)
{
    if(obj!=null)
    {
        obj.style.backgroundColor=color;
    }
}

function changeBorderStyle(obj,style)
{
    if(obj!=null)
    {
        obj.style.border=style;
    }
}
/*Toggle text color*/
function toggleTextColor(obj,thiscolor,thatcolor)
{
    if(obj.style.color==thiscolor)
    {
        obj.style.color=thatcolor;
    }
    else
    {
        obj.style.color=thiscolor;
    }
}


/*-----------------------------------------------------------------------
                            COOKIES FUNCTION
------------------------------------------------------------------------*/
/*cookie*/
function getCookie(name) 
{
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) 
	{
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function setCookie(name, value, expires, path, domain, secure)
{
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) 
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+'='+escape( value ) +
		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );
}

function deleteCookie( name, path, domain ) 
{
	if ( getCookie( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) + ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}


/*-----------------------------------------------------------------------
                            OTHERS FUNCTION
------------------------------------------------------------------------*/

/*
 * Date Format 1.2.2
 * (c) 2007-2008 Steven Levithan <stevenlevithan.com>
 * MIT license
 * Includes enhancements by Scott Trenda <scott.trenda.net> and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */
var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && (typeof date == "string" || date instanceof String) && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date();
		if (isNaN(date)) throw new SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "d/m/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "HH:MM:ss' ngày 'd/m/yy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};


