﻿//Sayfayla ilgili fonksiyonlar başladı.
//-----------------------------------------------------------------------------------------

var liErrorTemplate = '<li class="coklu">{0}</li>';
var liErrorTemplateForOneMsg = '<li>{0}</li>';

var divAlertTemplate ='<div class="{2}" >'+
  '<div class="top"/></div>'+
   '<div class="mid">'+
     '{4}<#3#>{1}<br/>'+
       '<a href="javascript:;" onclick="new WindowObject().closeAlert();"><img border="0" style="margin-top: 10px;" src="/d/i/hata_ok.gif" /></a>'+
     '</#3#>'+
   '</div>'+
   '<div class="bot"/>'+
'</div>';

var divAlertTemplateForConfirm ='<div class="{2}" >'+
  '<div class="top"/></div>'+
   '<div class="mid">'+
     '{4}<#3#>{1}<br/>'+
       '<a href="javascript:;" onclick="ConfirmWindowResult(1);">'+
        '<img border="0" style="margin-top: 10px;" src="/d/i/hata_ok.gif" /></a>'+
        '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+
       '<a href="javascript:;" onclick="ConfirmWindowResult(0);">'+
        '<img border="0" style="margin-top: 10px;" src="/d/i/hata_cancel.gif" /></a>'+
     '</#3#>'+
   '</div>'+
   '<div class="bot"/>'+
'</div>';

function ConfirmWindowResult(value){
    if (value == 1){ // kabul edildi
        new WindowObject().closeAlert();
        
        if (confirmFunctionPrm1 == null)
            eval(confirmFunctionToCall)();
        else if (confirmFunctionPrm1 != null)
            eval(confirmFunctionToCall)(confirmFunctionPrm1);
        else if (confirmFunctionPrm2 != null)
            eval(confirmFunctionToCall)(confirmFunctionPrm1, confirmFunctionPrm2);
    }
    else{ // reddedildi
        confirmReturnValue = false;
        new WindowObject().closeAlert();
    } 
} 
    
function WindowObject(){
   
}

var confirmFunctionToCall = '', confirmFunctionPrm1, confirmFunctionPrm2;

WindowObject.prototype.confirm = function(message, functionToCall, functionPrm1, functionPrm2){
    confirmFunctionToCall = functionToCall;
    confirmFunctionPrm1 = functionPrm1;
    confirmFunctionPrm2 = functionPrm2;
    this.alert("Confirm", message);  
};

WindowObject.prototype.alert = function(header, message){
    if (header == 'Confirm')
        var _divAlerttemplate = divAlertTemplateForConfirm;
    else
        var _divAlerttemplate = divAlertTemplate;
    
    var messageList = message.split('|');
    var messageArray = '';
    
    for(var i=0; i<messageList.length; i++){
        if(messageList != '' && messageList != 'undefined'){
            if(messageList[i] != '' && messageList[i] != 'undefined'){                
                if (messageList.length > 1)
                    messageArray = messageArray + liErrorTemplate.replace('{0}', messageList[i]);
                else
                    messageArray = messageArray + liErrorTemplateForOneMsg.replace('{0}', messageList[i]);
            }
        }
    }
     if (header=='Info')
        {
          _divAlerttemplate = _divAlerttemplate.replace('{4}', '<h1>Bilgi</h1>');
          _divAlerttemplate = _divAlerttemplate.replace('{2}', 'hata_cont');
          _divAlerttemplate = _divAlerttemplate.replace(/#3#/gi, 'ul');
          _divAlerttemplate = _divAlerttemplate.replace('{5}', '');
        
    }else
        {
           
          _divAlerttemplate = _divAlerttemplate.replace('{4}', '<h1>Dikkat</h1>');
          _divAlerttemplate = _divAlerttemplate.replace('{2}', 'hata_cont');
          _divAlerttemplate = _divAlerttemplate.replace(/#3#/gi, 'ul');
          _divAlerttemplate = _divAlerttemplate.replace('{5}', '');
        } 
     
     
    //_divAlerttemplate = _divAlerttemplate.replace('{0}', header);
    _divAlerttemplate = _divAlerttemplate.replace('{1}', messageArray);
    documentOverlay.show('doc_overlay');
    
    var left = (screen.width - 400) / 2;
   	var top = (screen.height - 400) / 2;
   	var scrollPos = getScrollingPosition();
   	top = top + scrollPos[1];
   	
   	/*if(window.navigator.appName == "Microsoft Internet Explorer")
        top = top + document.documentElement.scrollTop;
    else top = top + document.body.scrollTop;*/
   	
    var newdiv = document.createElement('div');
    newdiv.setAttribute('id', 'divError');
    newdiv.style.position = 'absolute'
    newdiv.style.zIndex = 1000;
   	newdiv.style.left = left + 'px';
   	newdiv.style.top = top + 'px';
   
   newdiv.innerHTML = _divAlerttemplate;
   document.getElementsByTagName('body')[0].appendChild(newdiv);
};

WindowObject.prototype.closeAlert = function(){
    documentOverlay.hide('doc_overlay');
    
    var obj = document.getElementById('divError');
    if (obj != null)
        document.body.removeChild(obj);
}

WindowObject.prototype.closeAlertData = function(){
    documentOverlay.hide('doc_alertData');
    
    var obj = document.getElementById('divAlertData');
    if (obj != null)
        document.body.removeChild(obj);
}

WindowObject.prototype.errorAlert = function(message){
    try { BizNet.Business.Ajax.Log.InsertAlertWindowLog(message); }
    catch(err) { }
    
    this.alert("Alert", message);
    
    //setTimeout("new WindowObject().closeAlert();", 2000);
};

WindowObject.prototype.errorAlertNotClose = function(message){
    try { BizNet.Business.Ajax.Log.InsertAlertWindowLog(message); }
    catch(err) { }
    
    this.alert("Alert", message);
};

WindowObject.prototype.infoAlert = function(message){
    try { BizNet.Business.Ajax.Log.InsertAlertWindowLog(message); }
    catch(err) { }
    
    this.alert("Info", message);
    //setTimeout("new WindowObject().closeAlert();", 2000);
};

WindowObject.prototype.infoAlertNotClose = function(message){
    try { BizNet.Business.Ajax.Log.InsertAlertWindowLog(message); }
    catch(err) { }
    
    this.alert("Info", message);
};

WindowObject.prototype.resultControl = function(result){
    if (result.ResultId == 1)
    {;}
    else if(result.ResultId == 3)
    {
        redirectToLoginPage();
    }
    else
    {
        this.errorAlert(result.ResultText);
    }
};

var documentOverlay = {    show: function(objId) {        
var color = 'Gray';
var opacity = 0.5;

// ---------------------        
//var o = document.getElementById('doc_overlay');        
var o = document.getElementById(objId);        
//var iframe = document.getElementById('doc_overlayFrame');  
if(!o) {            
    /*var o = document.createElement('div');            
    o.id = "doc_overlay";            
    documentOverlay.style(o,{                
        position: 'absolute',                
        top: 0,                
        left: 0,                
        width: '100%',                
        height: documentOverlay.getDocHeight()+'px',                
        background: color,                
        zIndex: 990,                
        opacity: opacity,                
        filter: 'alpha(opacity='+opacity*100+')',
        hasLayout: 1        
    });*/
    
    var o = document.createElement('iframe');
    o.src = '/blank.htm';
    o.id = objId;//"doc_overlay";
    documentOverlay.style(o,{                
        position: 'absolute',                
        top: 0,                
        left: 0,                
        width: '99.7%',                
        height: documentOverlay.getDocHeight()+'px',                
        //background: color,                
        zIndex: 900,                
        opacity: opacity,                
        filter: 'alpha(opacity='+opacity*100+')',
        hasLayout: 1        
    });
    
    //document.getElementsByTagName('body')[0].appendChild(iframe);
    document.getElementsByTagName('body')[0].appendChild(o);        
} else {            
    //documentOverlay.style(iframe,{background:color||'#000',display:'block'});        
    documentOverlay.style(o,{display:'block'});
    }    
},    
hide: function(objId) {        
    //var o = document.getElementById('doc_overlay');        
    var o = document.getElementById(objId);
    o.style.display = 'none';  
    //var iframe = document.getElementById('doc_overlayFrame');        
    //iframe.style.display = 'none';   
},    
style: function(obj,s) {        
    for ( var i in s ) {            
    obj.style[i] = s[i];        
    }    
},    
getDocHeight: function() {        
    var Y,YT;        
    if( self.innerHeight ) {
        Y = self.innerHeight;}        
    else if (
        document.documentElement && document.documentElement.clientHeight) {
            Y = document.documentElement.clientHeight;}         
            if( document.body ) {YT = document.body.clientHeight;}        
                if(YT>Y) {Y = YT;}        
                return Y;    
            }}

//Genel yardımcı fonksiyonlar başlıyor
//---------------------------------------------------------------------------------

function windowClose(){
    window.close();
}

function redirectToLogin(){
    window.location.href = 'Default.aspx?aType=Login';
}

function redirectToPage(pageUrl){
    setTimeout("window.location.href = '" + pageUrl + "';", 50);
}

function refreshPage(){
    setTimeout("window.location.href = 'window.location.href';", 50);
}

function addOnloadFunction(objFunction){
    if(typeof(objFunction) != 'function')return;
    
    var oldonload = window.onload;   

    if (typeof(window.addEventListener) == 'function')
    {
      window.addEventListener("load", objFunction, false); // firefox
    }
   else if (typeof window.onload != 'function') {   
     window.onload = objFunction;
   } 
   else {   
        window.onload = function() {   
       if (oldonload) {   
         oldonload();   
       }   
       objFunction();
     }
   }   
}


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)
        {
        position = [
        document.documentElement.scrollLeft,
        document.documentElement.scrollTop
        ];
    }
    else if (typeof document.body.scrollTop != 'undefined')
    {
        position = [
        document.body.scrollLeft,
        document.body.scrollTop
        ];
    }
    return position;
}

/*Querystring*/
//Su an icin sadece tek param'a ait degeri donduruyor.
//function  GetQueryString()
//{
// var value;
// var srch = window.location.search;
// var Pairs = srch.split('&');
// for (var i=1; i < Pairs.length; i++)
// {
//  if(i == 1)
//  {
//   var str = Pairs[i];
//   var x = str.indexOf('=');
//   var y = str.length;
//   value = str.substring(x+1,y);
//  }
// }
//return  value;
//}

/*function  GetQueryString(param)
{
 var value;
 var srch = window.location.search;
 var Pairs = srch.split('?');
 for (var i=1; i < Pairs.length+1; i++)
 {
  if(i == 1)
  {
   var str = Pairs[i];
   var params = str.split('&');
   for (var i=1; i < params.length+1; i++)
   {
       var par = params[i].split('=');
       if(par[1]==param);
        value = par[2];
   }
  }
 }
return  value;
}*/

function GetQueryString(param) {
    hu = window.location.search.substring(1);
    gy = hu.split('&');
    
    for (i=0;i<gy.length;i++) {
        ft = gy[i].split('=');
        if (ft[0].toLowerCase() == param.toLowerCase()) {
            return ft[1];
        }
    }
    
    return '';
}

function resizeOuterTo(w,h) {
 if (parseInt(navigator.appVersion)>3) {
   if (navigator.appName=="Netscape") {
    top.outerWidth=w;
    top.outerHeight=h;
   }
   else top.resizeTo(w,h);
 }
}
    
    
function onFocusSetEmpty(object, initialValue){
    if(object.value == initialValue){
        object.value = "";
    }
}

function onBlurSetDefault(object, initialValue){
    if(object.value == ""){
        object.value = initialValue;
    }
}

 function countLeft(obj, objCountId, max) {
     var objCount = document.getElementById(objCountId);
     // if the length of the string in the input field is greater than the max value, trim it 
     if (obj.value.length > max){
        obj.value = obj.value.substring(0, max);
        
        if(objCount.value)objCount.value = max - obj.value.length;
         else if(objCount.innerHTML)objCount.innerHTML = max - obj.value.length;
     }
     else{
         // calculate the remaining characters  
         if(objCount.value)objCount.value = max - obj.value.length;
         else if(objCount.innerHTML)objCount.innerHTML = max - obj.value.length;
     }
 }
 
 function getDayList(objectId, firstItemText, selectedValue){
   var selectedIndex = 0;
   var objDdl = document.getElementById(objectId);
   for(var i=objDdl.length-1; i>-1;i--)objDdl.remove(i);
   
   var optnFirst = document.createElement('option');
   optnFirst.text=firstItemText;
   optnFirst.value='0';
   objDdl.options.add(optnFirst);
   
   for(var i=1; i < 32; i++){
        var optn = document.createElement('option');
        optn.text = i.toString();
        optn.value = i.toString();
        
        if(optn.value == selectedValue){
            selectedIndex = i;
        }
        
        objDdl.options.add(optn);
   }
   
   objDdl.options[selectedIndex].selected = true;
 }
 
 function getMonthList(objectId, firstItemText, selectedValue){
   var selectedIndex = 0;
   var count = 1;
   var months = new Array('Ocak','Şubat','Mart','Nisan','Mayıs','Haziran','Temmuz','Ağustos','Eylül','Ekim','Kasım','Aralık');
   var objDdl = document.getElementById(objectId);
   for(var i=objDdl.length-1; i==0;i--)objDdl.remove(i);
   var optnFirst = document.createElement('option');
    optnFirst.text=firstItemText;
    optnFirst.value='0';
    objDdl.options.add(optnFirst);
   //$(objectId).erase('text');$(objectId).erase('value');
   /*var optnFirst = new Element('OPTION');
   optnFirst.text=firstItemText;
   optnFirst.value='0';
   $(objectId).options.add(optnFirst);*/
   
   for(var i=0; i < months.length; i++){
        var optn = document.createElement('option');
        optn.text = months[i];
        optn.value = (i+1).toString();
        
        if(optn.value == selectedValue){
            selectedIndex = count;
        }
        
        objDdl.options.add(optn); 
        count = count + 1;
   }
   
   objDdl.options[selectedIndex].selected = true;
 }
 
  function getYearList(objectId, firstItemText, selectedValue, beginDate, endDate){
   var selectedIndex = 0;
   var count = 1;
   var objDdl = document.getElementById(objectId);
   for(var i=objDdl.length-1; i==0;i--)objDdl.remove(i);
   var optnFirst = document.createElement('option');
    optnFirst.text=firstItemText;
    optnFirst.value='0';
    objDdl.options.add(optnFirst);
   /*$(objectId).erase('text');$(objectId).erase('value');
   var optnFirst = new Element('OPTION');
   optnFirst.text=firstItemText;
   optnFirst.value='0';
   $(objectId).options.add(optnFirst);*/
   
   for(var i=beginDate; i < endDate; i++){
        var optn = document.createElement('option');
        optn.text = i.toString();
        optn.value = i.toString();
        
        if(optn.value == selectedValue){
            selectedIndex = count;
        }
        
        objDdl.options.add(optn); 
        count = count + 1;
   }
   
   objDdl.options[selectedIndex].selected = true;
 }
 
//--►Üyelik adımlarının örnek 1,2,3 src lerini değiştiriyor

function ChangeImage(ElementId,value)
{
  var imgsrc   = "d/i/uye_no_{values}.gif";
  var imgvalue ={values:value};
  $(ElementId).setProperty('src',imgsrc.substitute(imgvalue));
}


//prevImg:ok_gerikare
//nextImg:ok_ilerikare
function getNumberList(prevImg, nextImg, divObjId, pageIndex, pageCount, rowCount){
    pageIndex = parseInt(pageIndex);
    pageCount = parseInt(pageCount);
    rowCount = parseInt(rowCount);
	var html = '';
	var btn1 = '';
	var btn2 = '';
	var _prev = parseInt(pageIndex-1);
	var _next = parseInt(pageIndex+1);
	
	
	var pagingBorder = pageCount;
	var activeBorderBegin = 1;
	var activeBorderEnd = pageCount;
	var pageBorderFactor = 1;
	
	if(pageCount > rowCount){
		html = html + '<STRONG>1</STRONG>';
		return html;
	}
	else{
		var linkCount = parseInt(rowCount / pageCount);
		var linkBalance = rowCount % pageCount;
		
		if(linkBalance > 0)linkCount = linkCount + 1;
		
		if(pageIndex > 1){
			btn1 = '<li><IMG height="14" onclick="nextPage(\''+String(divObjId)+'\',\''+String(_prev)+'\',\''+String(rowCount)+'\');" alt="geri" src="d/i/'+prevImg+'.gif" width="25" style="cursor:pointer;" /></li>';
		}
		
		if(pageIndex < linkCount){
			btn2 = '<li><IMG height="14" onclick="nextPage(\''+String(divObjId)+'\',\''+String(_next)+'\',\''+String(rowCount)+'\');" alt="ileri" src="d/i/'+nextImg+'.gif" width="25" style="cursor:pointer;" /></li>';
		}
		
		activeBorderBegin = parseInt(pageIndex / pagingBorder);
		
		if(activeBorderBegin == 0)activeBorderBegin = 1;
		else activeBorderBegin = (activeBorderBegin*pagingBorder)-1;
		
		if((activeBorderBegin + (pagingBorder-1)) >= (linkCount+1))activeBorderEnd = linkCount+1;
		else{
			if(activeBorderBegin < (pagingBorder-1))
				activeBorderEnd = activeBorderBegin + pagingBorder;
			else activeBorderEnd = activeBorderBegin + (pagingBorder + 2);
		}
		
		if(activeBorderEnd>(linkCount+1))
		    activeBorderEnd = (linkCount+1)
		
		for(var i=activeBorderBegin; i<activeBorderEnd; i++){
			if(pageIndex == i){
				if(html == '')html = html + '<STRONG>'+i+'</STRONG>';
				else html = html + ' | <STRONG>'+i+'</STRONG>';
			}
			else{
				if(html == '')html = html + '<A href="javascript:;" onclick="javascript:nextPage(\''+String(divObjId)+'\',\''+i+'\',\''+String(rowCount)+'\');">'+i+'</A>';
				else html = html + ' | <A href="javascript:;" onclick="javascript:nextPage(\''+String(divObjId)+'\',\''+i+'\',\''+String(rowCount)+'\');">'+i+'</A>';
			}
		}
	}
	
	return '<ul><li>' + btn1 + '</li><li>' + html + '</li><li>' + btn2 + '</li></ul>';
}

function getNumberList2(prevImg, nextImg, divObjId, pageIndex, pageCount, rowCount){
    pageIndex = parseInt(pageIndex);
    pageCount = parseInt(pageCount);
    rowCount = parseInt(rowCount);
	var html = '';
	var btn1 = '';
	var btn2 = '';
	var _prev = parseInt(pageIndex-1);
	var _next = parseInt(pageIndex+1);
	var fark = 0;
	var ilkSayfa = 0;
	var sayfaSayisi = 10;
	
	var pagingBorder = pageCount;
	var activeBorderBegin = 1;
	var activeBorderEnd = pageCount;
	var pageBorderFactor = 1;
	
	if(pageCount > rowCount){
		html = '';
		return html;
	}
	
    var linkCount = parseInt(rowCount / pageCount);
    var linkBalance = rowCount % pageCount;
	
    if(linkBalance > 0)
        linkCount = linkCount + 1;
	
    if(pageIndex > 1){
        btn1 = '<li><a href="javascript:nextPage(\''+String(divObjId)+'\',\''+String(1)+'\',\''+String(rowCount)+'\');"><strong>««</strong></a></li>';
	    btn1 = btn1 + '<li class="geri"><a href="javascript:nextPage(\''+String(divObjId)+'\',\''+String(_prev)+'\',\''+String(rowCount)+'\');"><strong>«</strong> önceki</a></li>';
    }
	
    if(pageIndex < linkCount){
        btn2 = '<li class="ileri"><a href="javascript:nextPage(\''+String(divObjId)+'\',\''+String(_next)+'\',\''+String(rowCount)+'\');">sonraki <strong>»</strong></a></li>';
        btn2 = btn2 + '<li><a href="javascript:nextPage(\''+String(divObjId)+'\',\''+String(linkCount)+'\',\''+String(rowCount)+'\');"><strong>»»</strong></a></li>';
    }
    
    fark = sayfaSayisi / 2;
    activeBorderBegin = pageIndex - fark + 1;
    if (activeBorderBegin <= 0)
        activeBorderBegin = 1;
    activeBorderEnd = activeBorderBegin + sayfaSayisi - 2;
    if (activeBorderEnd > linkCount)
        activeBorderEnd = linkCount;       
            
    // sayfa ilk yüklendiğinde paging 10 a kadar gitsin ...
    if ((activeBorderEnd == (sayfaSayisi - 1)) && (activeBorderEnd < linkCount)){
          activeBorderEnd = sayfaSayisi ;
          ilkSayfa = 1;
    }
    else{
        ilkSayfa = 0;
    }
          
    if ((activeBorderEnd - activeBorderBegin) < (sayfaSayisi - 2))
        activeBorderBegin = (activeBorderEnd - (sayfaSayisi - 2)) + ilkSayfa;
    if (activeBorderBegin <= 0)
        activeBorderBegin = 1;
    
    var liClass ;
    for(var i=activeBorderBegin; i<=activeBorderEnd; i++){
	    if (i == activeBorderEnd)
            liClass = '';
        else
            liClass = ' class="border"';
	     
        if(pageIndex == i){
		    html = html + '<li'+liClass+'><a href="javascript:;" class="current">'+i+'</a></li>';
	    }
	    else{
		    html = html + '<li'+liClass+'><a href="javascript:nextPage(\''+String(divObjId)+'\',\''+i+'\',\''+String(rowCount)+'\');">'+i+'</a></li>';
	    }
    }

    html = '<ul class="pages">' + btn1 + html + btn2 + '</ul>';
	
	return html;
}

function getTotalPageCount(pageIndex, pageCount, rowCount){
    pageIndex = parseInt(pageIndex);
    pageCount = parseInt(pageCount);
    rowCount = parseInt(rowCount);
    var linkCount = parseInt(rowCount / pageCount);
    var linkBalance = rowCount % pageCount;
	
    if(linkBalance > 0)linkCount = linkCount + 1;
    if(linkCount == 0)linkCount = linkCount + 1;	
    
	return 'sayfa ' + pageIndex.toString() + '/' + linkCount.toString();
}

function WritePagerHtml(currentPage, totalResults, link, Geri, Ileri)
{
    var little = '<';
    var greater = '>';  


    var verStartIndex = link.search(/ver/i);
    if(verStartIndex > 0)
    {
        link = link.substring(0, verStartIndex - 1);        
    }

    var startIndex = link.search(/page/i);
    if(startIndex > 0)
    {
      link = link.substring(0, startIndex - 1);
    }
    link = link + amp + 'Page=';

            
    var previousPage = currentPage - 1;
    var nextPage = currentPage + 1;
    var pageTaban = currentPage - 2;
    var pageTavan = currentPage + 2;
    var totalPageCount = totalResults;

    if(pageTaban < 1 )
    {
      pageTaban = 1;
      pageTavan = pageTaban + 4;
    }

    if(pageTavan > totalPageCount )
    {
      pageTavan = totalPageCount;
      if(pageTavan > 5)
      {
        pageTaban = pageTavan - 4;      
      }
      else
      {
        pageTaban = 1;            
      }
    }
            
    var pageHtml = '';
    if(pageTaban != pageTavan)
    {
    pageHtml += '<ul>' 
        if(currentPage > 1)
        {
         pageHtml += '<li>' 

          pageHtml += little + 'a href=\"'+ link + previousPage +'\"' + greater+ '' + Geri;
          pageHtml += little + '/a'+ greater+ ' ';
          
          pageHtml += '</li>';
        }

                            

        for(i = pageTaban; i <= pageTavan;i++ )
        {   
        pageHtml += '<li>'                                  
            if(currentPage != i)
            {                  
              pageHtml += little + 'a href=\''+link+''+i+'\''+greater+''+i+little+'/a'+greater+'';                  
            }
            else
            {
              pageHtml += little + 'a class="current" href="javascript:;"' + greater + i + little + '/a' + greater + '';
            }
            if(i != pageTavan)
              pageHtml +=  ' | ';                
        pageHtml += '</li>'
        }
        
                             
        
        
        if(currentPage < totalPageCount)
        {
         pageHtml += '<li>'
            pageHtml += little + 'a href=\"'+ link + nextPage +'\"' + greater+ '' + Ileri;
            pageHtml += little + '/a'+ greater+ ' ';
          pageHtml += '</li>'
        }  
        
          pageHtml += '</ul>'        
    }
    document.write(pageHtml); 
}

function loading(divId){
    /*if(document.getElementById(divId)){
        var obj = document.getElementById(divId);
        var newdiv = document.createElement('div');
        newdiv.setAttribute('class', 'ajaxFx');
        var newSubdiv = document.createElement('div');
        
        newSubdiv.setAttribute('class', 'ajaxLoader');
        newSubdiv.setAttribute('id', 'divAjaxLoader');
        newdiv.appendChild(newSubdiv);
        obj.innerHTML = '';
        obj.appendChild(newSubdiv);
        alert(obj.innerHTML);
    }*/
    
    var html = '<div class="ajaxFx" ><div class="ajaxLoader" id="divAjaxLoader" /></div>';
    if(document.getElementById(divId))
        document.getElementById(divId).innerHTML = html;
}


function redirectToLoginPage(){
    window.location.href = "/Default.aspx?aType=login";
}

function Trim(text) {
	return text.replace(/^\s+|\s+$/g,"");
}


function OpenCloseDiv(id)
{
    if(document.getElementById(id).style.display == 'none')
        document.getElementById(id).style.display = 'block'
    else
        document.getElementById(id).style.display = 'none'

}

function OpenCloseObjectsLikeName(idPrefix, objectType)
{
    var objList = document.getElementsByTagName(objectType);
    
    for(i=0; i<objList.length; i++){
        if(objList[i].id.indexOf(idPrefix) > -1){
            if(objList[i].style.display == 'none')objList[i].style.display = 'block';
            else objList[i].style.display = 'none';
        }
    }
}

var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var base64DecodeChars = new Array(
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
    -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
    -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);
    
function base64decode(str) {
    var c1, c2, c3, c4;
    var i, len, out;

    len = str.length;
    i = 0;
    out = "";
    while(i < len) {
	/* c1 */
	do {
	    c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
	} while(i < len && c1 == -1);
	if(c1 == -1)
	    break;

	/* c2 */
	do {
	    c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
	} while(i < len && c2 == -1);
	if(c2 == -1)
	    break;

	out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));

	/* c3 */
	do {
	    c3 = str.charCodeAt(i++) & 0xff;
	    if(c3 == 61)
		return out;
	    c3 = base64DecodeChars[c3];
	} while(i < len && c3 == -1);
	if(c3 == -1)
	    break;

	out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));

	/* c4 */
	do {
	    c4 = str.charCodeAt(i++) & 0xff;
	    if(c4 == 61)
		return out;
	    c4 = base64DecodeChars[c4];
	} while(i < len && c4 == -1);
	if(c4 == -1)
	    break;
	out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
    }
    return out;
}

function getImageFromBase64(imageId, base64Image){
    var data = base64decode(base64Image);
    document.getElementById(imageId).src = 'data:image/gif;base64,' + data;
}

function textCounter(field, cntfield, maxlimit) {
//alert(field.value.length)
    if (field.value.length > maxlimit) // if too long...trim it!
        field.value = field.value.substring(0, maxlimit);
    // otherwise, update 'characters left' counter
    else{
           if(cntfield)
                cntfield.innerHTML = (maxlimit - field.value.length) + ' karakter'  ;
    }
}


function makeURL(nod)
{
var title = encodeURI(document.getElementById('hiddenTitle').value);
var url = escape(document.getElementById('hiddenURL').value);
var options = "height=700,width=800,titlebar=no,status=no,toolbar=no,menubar=no,location=no,resizable=no,scrollbars=1";
var mURL='';
if(nod==1)
mURL="http://www.facebook.com/sharer.php?u=" + url + "&amp;title=" + title;
if(nod==2)
mURL="http://www.google.com/bookmarks/mark?op=edit&#38;bkmk=" + url + "&#38;title=" + title;
if(nod==3)
mURL="http://myweb2.search.yahoo.com/myresults/bookmarklet?&amp;u=" +url+ "&amp;t=" + title;
if(nod==4)
mURL="http://www.mixx.com/submit/story?title="+title+"&amp;page_url="+url+"&amp;partner=bizebiz&amp;description=";
if(nod==5)
mURL="http://digg.com/submit?url="+url+"&amp;title=" + title;
if(nod==6)
mURL="http://www.stumbleupon.com/submit?url="+url+"&amp;title=" + title;
if(nod==7)
mURL="http://del.icio.us/post?url="+url+"&amp;title=" + title;
if(nod==8)
mURL="http://reddit.com/submit?url="+url+"&amp;title=" + title;
if(nod==9)
mURL="//twitter.com/home?status="+title+" "+url;
//mURL="http://twshot.com/share.aspx?url="+url+"&amp;title=" + title;
if(nod==10)
mURL="http://www.myspace.com/Modules/PostTo/Pages/?l=2&amp;u=" +url+ "&amp;t="+title+"&amp;c="+title;
if(nod==11)
mURL="http://friendfeed.com/share/bookmarklet/frame#title=" + title + "&amp;url="+url;

window.open(mURL.replace(/amp;/gi,''),'_blank',options);
}

 function shareTwitter(articleID){
          var title = encodeURI(document.getElementById('hiddenTitle').value);
          var url = escape(document.getElementById('hiddenURL').value);
          var options = "height=700,width=800,titlebar=no,status=no,toolbar=no,menubar=no,location=no,resizable=no,scrollbars=1";
          window.open('http://twitter.com/home?status='+title+' '+url+articleID,'_blank',options);
          
      }


function removeObject(id){
    var obj = document.getElementById(id);
    obj.parentNode.removeChild(obj);
}

function replaceObject(newObj, oldObjId){
    var oldObj = document.getElementById(oldObjId);
    oldObj.parentNode.replaceChild(newObj, oldObj);
}

//--------------Image Load-----------------
//source: http://snipplr.com/view.php?codeview&id=561
// Cross-browser implementation of element.addEventListener()
function addListener(element, type, expression, bubbling)
{
  bubbling = bubbling || false;
  if(window.addEventListener)	{ // Standard
    element.addEventListener(type, expression, bubbling);
    return true;
  } else if(window.attachEvent) { // IE
    element.attachEvent('on' + type, expression);
    return true;
  } else return false;
}

var ImageLoader = function(url){
  this.url = url;
  this.image = null;
  this.loadEvent = null;
};

ImageLoader.prototype = {
  load:function(){
    this.image = document.createElement('img');
    var url = this.url;
    var image = this.image;
    var loadEvent = this.loadEvent;
    addListener(this.image, 'load', function(e){
      if(loadEvent != null){
        loadEvent(url, image);
      }
    }, false);
    this.image.src = this.url;
  },
  getImage:function(){
    return this.image;
  }
};

var imgObj;
function AsyncImageLoad(imgId, imgUrl, imgWidth, imgHeight, imgAlt, imgClass, imgStyle){
  
  
    var loader = new ImageLoader(imgUrl);

    loader.loadEvent = function(url, image){
        //var dtImg = document.getElementById(imgId);
        //alert(imgHeight);
        if(typeof(imgWidth) != 'undefined'){
            if(imgWidth.length > 0)image.width = parseInt(imgWidth);
        }
        
        if(typeof(imgHeight) != 'undefined'){
            if(imgHeight.length > 0)image.height = parseInt(imgHeight);
        }
        if(typeof(imgAlt) != 'undefined'){
            if(imgAlt.length > 0)image.alt = imgAlt;
        }
        
        if(typeof(imgClass) != 'undefined'){
            if(imgClass.length > 0)image.className = imgClass;
        }
        
        if(typeof(imgStyle) != 'undefined'){
            if(imgStyle.length > 0)image.style = imgStyle;
        }
        
        image.id=imgId;
        //alert(image.width);
        //image.className = "captcha";
//       while(dtImg.firstChild){
//            dtImg.removeChild(dtImg.firstChild);
//       }
       //alert(image.id);
          
       replaceObject(image, imgId);
    }
     
    loader.load();
}

function OpenMyFriendsConnections(memberId){
    var pageCount;
    pageCount = 5;

    OpenCommonList(memberId, 1, pageCount, 4);    
}

function OpenCommonConnections(memberId){
    var pageCount;
    pageCount = 5; 

    OpenCommonList(memberId, 1, pageCount, 1);    
}

function OpenCommonGroupMyFriendList(groupId){
    var pageCount;
    pageCount = 5;
    
    OpenCommonList(groupId, 1, pageCount, 2);  
}

function OpenCommonOppJoinList(oppId){
    var pageCount;
    pageCount = 5;
    
    OpenCommonList(oppId, 1, pageCount, 3);  
}

function OpenCommonList(sourceId, pageIndex, pageCount, type){    
    /*
        type - 1 : Ortak Bağlantı Listesi
        type - 2 : Gruptaki Arkadaş Listesi 
        type - 3 : Fırsat Katılımcı Listesi 
        type - 4 : Arkadaşının Arkadaş Listesi
    */
    
    var listUtilityName = '';
    var xslParsedLists = new XslParsedLists();
    xslParsedLists.KeyValueForXsl('objTypeId', type);
    xslParsedLists.KeyValueForXsl('objSourceId', sourceId);
    
    xslParsedLists.KeyValue('PageCount', pageCount);
    xslParsedLists.KeyValue('PageIndex', pageIndex);      
        
    if (type == '1'){        
        xslParsedLists.KeyValue('MemberId', sourceId);
        listUtilityName = 'CommonConnectionsListWithBox';
    }
    else if (type == '2'){        
        xslParsedLists.KeyValue('GroupId', sourceId);
        listUtilityName = 'GroupMyFriendListWithBox';
    }
    else if (type == '3'){        
        xslParsedLists.KeyValue('OpportunityId', sourceId);
        listUtilityName = 'OpportunutiyJoinListWithBox';
    }
    else if (type == '4'){        
        xslParsedLists.KeyValue('MemberId', sourceId);
        listUtilityName = 'MyFriendLinksWithBox';
    }
    
    loading('divAlertPagedData');
    xslParsedLists.GetListsForAlert(listUtilityName); 
}

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    } else {
        var expires = "";
    } 
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') {
            c = c.substring(1,c.length);
        }

        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length,c.length);
        }
    }
    return null;
}

window.linkify = (function(){
  var
    SCHEME = "[a-z\\d.-]+://",
    IPV4 = "(?:(?:[0-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])\\.){3}(?:[0-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])",
    HOSTNAME = "(?:(?:[^\\s!@#$%^&*()_=+[\\]{}\\\\|;:'\",.<>/?]+)\\.)+",
    TLD = "(?:ac|ad|aero|ae|af|ag|ai|al|am|an|ao|aq|arpa|ar|asia|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|biz|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|cat|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|coop|com|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|info|int|in|io|iq|ir|is|it|je|jm|jobs|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mobi|mo|mp|mq|mr|ms|mt|museum|mu|mv|mw|mx|my|mz|name|na|nc|net|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pro|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tel|tf|tg|th|tj|tk|tl|tm|tn|to|tp|travel|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|xn--0zwm56d|xn--11b5bs3a9aj6g|xn--80akhbyknj4f|xn--9t4b11yi5a|xn--deba0ad|xn--g6w251d|xn--hgbk6aj7f53bba|xn--hlcj6aya9esc7a|xn--jxalpdlp|xn--kgbechtv|xn--zckzah|ye|yt|yu|za|zm|zw)",
    HOST_OR_IP = "(?:" + HOSTNAME + TLD + "|" + IPV4 + ")",
    PATH = "(?:[;/][^#?<>\\s]*)?",
    QUERY_FRAG = "(?:\\?[^#<>\\s]*)?(?:#[^<>\\s]*)?",
    URI1 = "\\b" + SCHEME + "[^<>\\s]+",
    URI2 = "\\b" + HOST_OR_IP + PATH + QUERY_FRAG + "(?!\\w)",
    
    MAILTO = "mailto:",
    EMAIL = "(?:" + MAILTO + ")?[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@" + HOST_OR_IP + QUERY_FRAG + "(?!\\w)",
    
    URI_RE = new RegExp( "(?:" + URI1 + "|" + URI2 + "|" + EMAIL + ")", "ig" ),
    SCHEME_RE = new RegExp( "^" + SCHEME, "i" ),
    
    quotes = {
      "'": "`",
      '>': '<',
      ')': '(',
      ']': '[',
      '}': '{',
      'Â»': 'Â«',
      'â€º': 'â€¹'
    },
    
    default_options = {
      callback: function( text, href ) {
        return href ? '<a href="' + href + '" target="_blank">' + text + '</a>' : text;
      },
      punct_regexp: /(?:[!?.,:;'"]|(?:&|&amp;)(?:lt|gt|quot|apos|raquo|laquo|rsaquo|lsaquo);)$/
    };
  
  return function( txt, options ) {
    options = options || {};
    
    // Temp variables.
    var arr,
      i,
      link,
      href,
      
      // Output HTML.
      html = '',
      
      // Store text / link parts, in order, for re-combination.
      parts = [],
      
      // Used for keeping track of indices in the text.
      idx_prev,
      idx_last,
      idx,
      link_last,
      
      // Used for trimming trailing punctuation and quotes from links.
      matches_begin,
      matches_end,
      quote_begin,
      quote_end;
    
    // Initialize options.
    for ( i in default_options ) {
      if ( options[ i ] === undefined ) {
        options[ i ] = default_options[ i ];
      }
    }
    
    // Find links.
    while ( arr = URI_RE.exec( txt ) ) {
      
      link = arr[0];
      idx_last = URI_RE.lastIndex;
      idx = idx_last - link.length;
      
      // Not a link if preceded by certain characters.
      if ( /[\/:]/.test( txt.charAt( idx - 1 ) ) ) {
        continue;
      }
      
      // Trim trailing punctuation.
      do {
        // If no changes are made, we don't want to loop forever!
        link_last = link;
        
        quote_end = link.substr( -1 )
        quote_begin = quotes[ quote_end ];
        
        // Ending quote character?
        if ( quote_begin ) {
          matches_begin = link.match( new RegExp( '\\' + quote_begin + '(?!$)', 'g' ) );
          matches_end = link.match( new RegExp( '\\' + quote_end, 'g' ) );
          
          // If quotes are unbalanced, remove trailing quote character.
          if ( ( matches_begin ? matches_begin.length : 0 ) < ( matches_end ? matches_end.length : 0 ) ) {
            link = link.substr( 0, link.length - 1 );
            idx_last--;
          }
        }
        
        // Ending non-quote punctuation character?
        if ( options.punct_regexp ) {
          link = link.replace( options.punct_regexp, function(a){
            idx_last -= a.length;
            return '';
          });
        }
      } while ( link.length && link !== link_last );
      
      href = link;
      
      // Add appropriate protocol to naked links.
      if ( !SCHEME_RE.test( href ) ) {
        href = ( href.indexOf( '@' ) !== -1 ? ( !href.indexOf( MAILTO ) ? '' : MAILTO )
          : !href.indexOf( 'irc.' ) ? 'irc://'
          : !href.indexOf( 'ftp.' ) ? 'ftp://'
          : 'http://' )
          + href;
      }
      
      // Push preceding non-link text onto the array.
      if ( idx_prev != idx ) {
        parts.push([ txt.slice( idx_prev, idx ) ]);
        idx_prev = idx_last;
      }
      
      // Push massaged link onto the array
      parts.push([ link, href ]);
    };
    
    // Push remaining non-link text onto the array.
    parts.push([ txt.substr( idx_prev ) ]);
    
    // Process the array items.
    for ( i = 0; i < parts.length; i++ ) {
      html += options.callback.apply( window, parts[i] );
    }
    
    // In case of catastrophic failure, return the original text;
    return html || txt;
  };
  
})();
