//	       _            
//	      (_)           
//	  __ _ _  __ ___  __
//	 / _` | |/ _` \ \/ /
//	| (_| | | (_| |>  < 
//	 \__,_| |\__,_/_/\_\
//	     _/ |           
//	    |__/     

var currentSelection = '';

var clearInt; // clear timeout

// wyslanie zapytania o kontakty
function grabContacts(that){
	if(isEmail($('grab_login').value)){
			startloading();
			var ps = new Array();									
			ps['grab_login'] = $('grab_login').value;											
			ps['grab_password'] = $('grab_password').value;	
			sndReq('grabber.php5', 'grab', ps);
	}else{
		showErrorMessage('Please use full login with domain name.');
	}
}

function isEmail(arg_text) {
	var reg_exp = new RegExp("^([a-zA-Z0-9+._-])+@([a-zA-Z0-9+._-])+[.]{1}[a-zA-Z]{2,4}$");
	if (reg_exp.test(arg_text))
		return true;
	else
		return false;
}

/**
 * Zarzadznie odpowiedzia
 **/
function dispatchResponse(data, responseTxt) {
	if (data[0] == 'error') {									// blad zwrcony przez RPC
		//alert('Error:\r\n'+data[1]);
		//setTimeout("clearGrabber()", 250);
		showErrorMessage(data[1]);
	}else if (data[0] == 'contactsGrabbed') {					// odebrane dane
		showGrabbedContacts(data[1]);
	}else if (data[0] == 'loginChallenge'){ 						// odebrane dane
		showLoginChallenge(data);
	}else{														// nieznana odpowiedz AJAX
		//alert('Unknown AJAX response: ' + responseTxt);
		//setTimeout("clearGrabber()", 250);
		showErrorMessage(responseTxt);
	}
}

//pokazanie listy grabnietych userow
function showGrabbedContacts(data){
		var iDek = data.split('^^');
		
		if(iDek.length > 0 && iDek[0].length>0 && iDek[1].length>0){
			var aNames = iDek[0].split('|');
			var aEmails = iDek[1].split('|');
			var maxLen = Math.min(aNames.length, aEmails.length);
			if($('grabResultTable')){
				var obj = $('grabResultTable');

				if(maxLen > 0){
					var innercja = '<table cellpadding="0" cellspacing="3" border="0" id="grabResultTableA">';
	
					innercja += '<tr><th colspan="3">Please now choose those of friends you want to send email to:</th></tr>';
	
					for(var c = 0; c < maxLen; c++){
					
						// generowanie kontakt�w
						innercja += '<tr id="emailRow_'+c+'">';
						innercja += '<td style="text-align: left"><input type="checkbox" name="grabbedContact['+c+']" id="grabbedContact_'+c+'" value="'+aEmails[c]+'" checked="checked" /></td>';
						innercja += '<td style="text-align: left"><label for="grabbedContact_'+c+'">'+aNames[c]+'</label></td>';
						innercja += '<td style="text-align: left"><label for="grabbedContact_'+c+'">'+aEmails[c]+'</label></td>';
						innercja += '</tr>';
					}
					innercja += '<tr><td style="text-align: left"><img src="/gfx/arrow_up.gif" alt="" /></td><td colspan="2" style="text-align: left; color: #999"><a href="#" onclick="switchSelection(1);" style="text-align: left; color: #999; text-decoration: underline">Select</a> /<a href="#" onclick="switchSelection(0);" style="text-align: left; color: #999; text-decoration: underline">deselect</a> all</label></td></tr>';
					
					innercja += '<tr><td colspan="3"><input type="button" class="grabber button" onclick="addGrabbedContacts();" value="&nbsp;" /></td></tr></table>';
					$('grabResultTable').innerHTML = innercja;
					
					if(maxLen > 5)
						$('grabResultTable').style.height = '400px';
					else
						$('grabResultTable').style.height = '170px';
				}
			}else{
				endloading();
			}
		}else{
			// info o braku kontakt�w
			emptyListInfo();
		}
	endloading();
}

// info o login challenge
function showLoginChallenge(data){
	endloading();
	clearGrabber();
	if($('captchaRow')){
		$('captchaRow').style.display = '';
		$('captchaRow').innerHTML = data[1];
		//var dane = data[1].split('_');
		//$('captchaImg').src = '../'+dane[1];
		//$('captchaDiv').innerHTML = 'Please retype text from image:';
		//$('gmail_captcha').value = '';
	}
}


// startuje loadera
function startloading(){
	
	if($('grabResultTable'))
		$('grabResultTable').style.display='none';

	if($('loginRow'))
		$('loginRow').style.display='none';
	if($('passwdRow'))
		$('passwdRow').style.display='none';
	if($('selectRow'))
		$('selectRow').style.display='none';
	if($('grabRow'))
		$('grabRow').style.display='none';
	
	if($('loadingRow'))
		$('loadingRow').style.display='';
}

// konczy loadera
function endloading(){
	$('grabTable').style.display='none';
	
	$('grabResultTable').style.display='';
}


// dodaje konatkty do listy mailungu
function addGrabbedContacts(){
	if($('grabResultTable')){
		var inputs = $('grabResultTable').getElementsByTagName('INPUT');
		var maxIns = inputs.length;
		if(maxIns > 0){
			var mailLista = new Array();
			for(var xx in inputs){
				// dodawanie
				if(inputs[xx] && inputs[xx].type == 'checkbox' && inputs[xx].value != '' && inputs[xx].checked) {
					if ($('remailDivAdd')) {
						divadd = $('remailDivAdd');
				
						var added = document.createElement('input');
						added.setAttribute('type', 'text');
						added.className = 'remail';
						added.setAttribute('id', 'remail');
						added.setAttribute('value', inputs[xx].value);
						added.setAttribute('name', 'remail[]');
						
						var divadded = document.createElement('div');
						divadded.className = 'leftmargin';
						
						divadded.setAttribute('id', 'divadded');
						divadd.appendChild(divadded).appendChild(added);
					}
				}	
//					mailLista.push('<div class="leftmargin"><input class="remail" id="remail" type="test" name="remail[]" value="' + inputs[xx].value + '" /></div>');
			}
			// dodanie do inputa mailingu
//			if($('remailDivAdd')){
//				var mailListaT = mailLista.unique();
//				var mailing = mailListaT.join('');
//				var rm = $('remailDivAdd');
//				rm.innerHTML += mailing;
//			}
			
			// podziekowania
			thankYouGrabber();
		}
		
	}
}


// zaznacz/odznacz wszystkie
function switchSelection(typ){
	if(typ == 1){ // zaznacz wszystkie
		var selCh = true;
	}else{ // odznacz
		var selCh = false;
	}
	
	var inputs = $('grabResultTable').getElementsByTagName('INPUT');
	var maxIns = inputs.length;
	if(maxIns > 0){
		for(var xx in inputs){
			// selekcja
			if(inputs[xx] && inputs[xx].type == 'checkbox')
				inputs[xx].checked = selCh;
		}
	}
}

// podziekowania
function thankYouGrabber(){
	if($('grabResultTable')){
		$('grabResultTable').innerHTML = '<table cellpadding="0" cellspacing="3" border="0" id="grabResultTableA"><tr><td style="text-align: center"><div class="thanks"><p>Thank You for using our service!</p><br /><p>Models Connect Team</p></div><a href="javascript:clearGrabber();">CLEAR WINDOW</a></td></tr></table>';
		// reset grabbera
		$('grabResultTable').style.height='170px';
		clearInt = setTimeout("clearGrabber()", 5000);
	}else{
		alert('Thank you for using our service.');
	}
}

// info o pustej liscie
function emptyListInfo(){
	if($('grabResultTable')){
		$('grabResultTable').innerHTML = '<table cellpadding="0" cellspacing="3" border="0" id="grabResultTableA"><tr><td style="text-align: center"><div class="continfo"><p>Unfortunately our system did not manage to find any contacts.<br />Probably because your list is empty.</p><br /><p>Models Connect Team</p></div><a href="javascript:clearGrabber();">CLEAR WINDOW</a></td></tr></table>';
		$('grabTable').style.display='none';
		$('grabResultTable').style.display='';
		$('grabResultTable').style.height='170px';
		// reset grabbera
		clearInt = setTimeout("clearGrabber()", 5000);
	}else{
		alert('Unfortunately our system did not manage to find any contacts. Probably because your list is empty.');
	}
}

function showErrorMessage(textMSG){
	if($('grabResultTable')){
		$('grabResultTable').innerHTML = '<table cellpadding="0" cellspacing="3" border="0" id="grabResultTableA"><tr><td style="text-align: center"><div class="errorinfo"><p>There was an error while grabbing your contacts:</p><p style="font-weight: bold">'+textMSG+'</p><p>Models Connect Team</p></div><a href="javascript:clearGrabber();">CLEAR WINDOW</a></td></tr></table>';
		$('grabTable').style.display='none';
		$('grabResultTable').style.display='';
		$('grabResultTable').style.height='170px';
		// reset grabbera
		clearInt = setTimeout("clearGrabber()", 5000);
	}else{
		alert('An error occured while processing your request: '+textMSG);
	}
}

// czyszczenie
function clearGrabber(){
	window.clearTimeout(clearInt);
	$('grabTable').style.display='';
	$('loginRow').style.display='';
	$('passwdRow').style.display='';
	//$('selectRow').style.display='';
	$('grabRow').style.display='';
	
	$('loadingRow').style.display='none';
	$('grabResultTable').style.display='none';
	$('grabResultTable').innerHTML = '';
	$('msn_selector').className = 'select';
	$('gmail_selector').className = 'select';
	$('grab_login').value = '';											
	$('grab_password').value = '';	
	currentSelection = '';
	
}




// -- Standard functions

// Array.concat() - Join two arrays
if( typeof Array.prototype.concat==='undefined' ) {
 Array.prototype.concat = function( a ) {
  for( var i = 0, b = this.copy(); i<a.length; i++ ) {
   b[b.length] = a[i];
  }
  return b;
  };
}

// Array.copy() - Copy an array
if( typeof Array.prototype.copy==='undefined' ) {
 Array.prototype.copy = function() {
  var a = [], i = this.length;
  while( i-- ) {
   a[i] = typeof this[i].copy!=='undefined' ? this[i].copy() : this[i];
  }
  return a;
 };
}

// Array.pop() - Remove and return the last element of an array
if( typeof Array.prototype.pop==='undefined' ) {
 Array.prototype.pop = function() {
  var b = this[this.length-1];
  this.length--;
  return b;
 };
}

// Array.push() - Add an element to the end of an array, return the new length
if( typeof Array.prototype.push==='undefined' ) {
 Array.prototype.push = function() {
  for( var i = 0, b = this.length, a = arguments, l = a.length; i<l; i++ ) {
   this[b+i] = a[i];
  }
  return this.length;
 };
}

// Array.shift() - Remove and return the first element
if( typeof Array.prototype.shift==='undefined' ) {
 Array.prototype.shift = function() {
  for( var i = 0, b = this[0], l = this.length-1; i<l; i++ ) {
   this[i] = this[i+1];
  }
  this.length--;
  return b;
 };
}

// Array.slice() - Copy and return several elements
if( typeof Array.prototype.slice==='undefined' ) {
 Array.prototype.slice = function( a, c ) {
  var i, l = this.length, r = [];
  if( !c ) { c = l; }
  if( c<0 ) { c = l + c; }
  if( a<0 ) { a = l - a; }
  if( c<a ) { i = a; a = c; c = i; }
  for( i = 0; i < c - a; i++ ) { r[i] = this[a+i]; }
  return r;
 };
}

// Array.splice() - Remove or replace several elements and return any deleted elements
if( typeof Array.prototype.splice==='undefined' ) {
 Array.prototype.splice = function( a, c ) {
  var i = 0, e = arguments, d = this.copy(), f = a, l = this.length;
  if( !c ) { c = l - a; }
  for( i; i < e.length - 2; i++ ) { this[a + i] = e[i + 2]; }
  for( a; a < l - c; a++ ) { this[a + e.length - 2] = d[a - c]; }
  this.length -= c - e.length + 2;
  return d.slice( f, f + c );
 };
}

// Array.unshift() - Add an element to the beginning of an array
if( typeof Array.prototype.unshift==='undefined' ) {
 Array.prototype.unshift = function() {
  this.reverse();
  var a = arguments, i = a.length;
  while(i--) { this.push(a[i]); }
  this.reverse();
  return this.length;
 };
}

// -- 4umi additional functions

// Array.forEach( function ) - Apply a function to each element
Array.prototype.forEach = function( f ) {
 var i = this.length, j, l = this.length;
 for( i=0; i<l; i++ ) { if( ( j = this[i] ) ) { f( j ); } }
};

// Array.indexOf( value, begin, strict ) - Return index of the first element that matches value
Array.prototype.indexOf = function( v, b, s ) {
 for( var i = +b || 0, l = this.length; i < l; i++ ) {
  if( this[i]===v || s && this[i]==v ) { return i; }
 }
 return -1;
};

// Array.insert( index, value ) - Insert value at index, without overwriting existing keys
Array.prototype.insert = function( i, v ) {
 if( i>=0 ) {
  var a = this.slice(), b = a.splice( i );
  a[i] = v;
  return a.concat( b );
 }
};

// Array.lastIndexOf( value, begin, strict ) - Return index of the last element that matches value
Array.prototype.lastIndexOf = function( v, b, s ) {
 b = +b || 0;
 var i = this.length; while(i-->b) {
  if( this[i]===v || s && this[i]==v ) { return i; }
 }
 return -1;
};

// Array.random( range ) - Return a random element, optionally up to or from range
Array.prototype.random = function( r ) {
 var i = 0, l = this.length;
 if( !r ) { r = this.length; }
 else if( r > 0 ) { r = r % l; }
 else { i = r; r = l + r % l; }
 return this[ Math.floor( r * Math.random() - i ) ];
};

// Array.shuffle( deep ) - Randomly interchange elements
Array.prototype.shuffle = function( b ) {
 var i = this.length, j, t;
 while( i ) {
  j = Math.floor( ( i-- ) * Math.random() );
  t = b && typeof this[i].shuffle!=='undefined' ? this[i].shuffle() : this[i];
  this[i] = this[j];
  this[j] = t;
 }
 return this;
};

// Array.unique( strict ) - Remove duplicate values
Array.prototype.unique = function( b ) {
 var a = [], i, l = this.length;
 for( i=0; i<l; i++ ) {
  if( a.indexOf( this[i], 0, b ) < 0 ) { a.push( this[i] ); }
 }
 return a;
};

// Array.walk() - Change each value according to a callback function
Array.prototype.walk = function( f ) {
 var a = [], i = this.length;
 while(i--) { a.push( f( this[i] ) ); }
 return a.reverse();
};

var id_number = 2;

function addtextbox(that) {
	if (that.value.length > 0) {
	
		
		divadd = $('remailDivAdd');
		var added = document.createElement('input');
		added.setAttribute('type', 'text');
		added.setAttribute('onkeyup', 'addtextbox(this);');
		added.onkeyup = function(){addtextbox(added);};
		added.setAttribute('name', 'remail[]');
		added.className = 'remail';
		var divadded = document.createElement('div');
		divadded.className = 'leftmargin';
		added.setAttribute('id', 'remail' + (id_number++));
		divadded.setAttribute('id', 'divadded' + id_number);
		divadd.appendChild(divadded).appendChild(added);
		that.onkeyup=function(){};
	}
}


	