Thursday 1 December 2011

13


<?php

require_once(COMM_PATH."facebook.php");

$facebook = new Facebook(array(
 'appId'  => APPID,
  'secret' => SECRET,
  'cookie' => true,
));


$session = $facebook->getSession();

$me = null;

if ($session) {
  try {
    $uid = $facebook->getUser();
    $me = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
  }
}

$loginUrl = $facebook->getLoginUrl(array(
  'req_perms' => 'email,user_birthday'));

?>

<div id="fb-root"></div>
    <script>
      window.fbAsyncInit = function() {
        FB.init({
          appId   : '<?php echo $facebook->getAppId(); ?>',
          session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
          status  : true, // check login status
          cookie  : true, // enable cookies to allow the server to access the session
          xfbml   : true // parse XFBML
        });

        // whenever the user logs in, we refresh the page
        FB.Event.subscribe('auth.login', function() {
          window.location.reload();
        });
      };

      (function() {
        var e = document.createElement('script');
        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        e.async = true;
        document.getElementById('fb-root').appendChild(e);
      }());
    </script>

<div style="display: none;" id="winhidelayer"></div>
<div class="popconatiner-2"  id="signinpopup" style="display:none;"> <strong></strong>        

<div class="blue_bar"></div>
 <div class="popupMain-Cont">

 <div class="popupMain-Cont-header">
     <h2>Have an Account?  <span style="color:#666;">Login Here.</span></h2>
      <!-- Btn Start Here -->
      <div class="Profile-pages-btn">
          <div class="greyBtnMain">
            <div class="greyBtnMain-left"></div>
            <div class="greyBtnMain-midd"><a href="#" title="Close" onclick="hideSigninPopup()">Close</a></div>
            <div class="greyBtnMain-Right"></div>
          </div>
        </div>
       <!-- Btn Ends Here -->
      <div class="clr"></div>
      </div>

<div class="form_div">

<form name="login" action="" method="post">
<div class="fields_div" id="Name">
<label >E-mail</label>
<input type="text" class="fields_tf" name="u_email" id="u_email" />
<div class="clr"></div>
</div>
<div class="fields_div">
<label >Password</label>
<input type="password" class="fields_tf" name="pword" id="pword" />
<div class="clr"></div>
</div>

<p><a href="#" onclick="return showforgetPopup()">Forgot your Password?</a></p>
<div class="clr"></div>
<div id='error1' style="display:none;" class="login_vld"></div>
<div id="login" class="login_vld"> </div>
<div class="clr"></div>

</div>
<div class="gray_line"><img src="<?php echo IMG_PATH ?>gry_line.jpg"  /></div>
<div class="sign_fb">
<div class="sg_fg_login"><a href="<?php echo $loginUrl; ?>"><img src="<?php echo IMG_PATH ?>facebookLogin-Btn.gif"></a></div>
<div class="sign_text">or</div>
<div class="sg_lgn_btn"><a href="javascript:;" onclick="return validateSignIn('u_email','pword','login');" id="submit">Login</a></div>
</div>
<input type="hidden" name="action" value="login_me" />
    </form>
<div class="clr"></div>
</div>
<div class="bottom_bg-1">
<h6>Don't Have an Account Yet? <span style="color:#666;">Sign Up Here.</span></h6>
<div class="gray_line"><img src="<?php echo IMG_PATH ?>gry_line.jpg"  /></div>
<div class="gray_2_login" ><a href="#" onclick="return showSignupPopup()">Sign Up Now</a></div>

<div class="clr"></div>
</div>
</div>

<script type="text/javascript">
function submitLogin(event){
if (event.keyCode == '13') {
    event.preventDefault();
    validateSignIn('u_email','pword','login');
}

}
$("#u_email").keypress(function(event){submitLogin(event);});
$("#pword").keypress(function(event){submitLogin(event);});
$("#submit").keypress(function(event){submitLogin(event);});
</script>

user init


<?php
require_once(ADMIN_LIB_PATH."user/userManager.php");
$userDetail = new userManager();//object for userManager class for accesing all function in userManager

//****************************PAGINATION START FROM HERE*********************************************
$numberOfRecordsPerPage = 2;
$minimumNumberOfPage = 1;
if(isset($_REQUEST['page']) && $_REQUEST['page']!=''){
$minimumNumberOfPage = $_REQUEST['page'];
}
$limitStartfrom = ($minimumNumberOfPage-1)*$numberOfRecordsPerPage;
//There is an object for count the number of record, From these we get number of page.................
$totalNumberOfRecords = $userDetail->count_User();
$totalNumberOfPages = ceil($totalNumberOfRecords/$numberOfRecordsPerPage);
$self = $_SERVER['PHP_SELF'];
if($minimumNumberOfPage>1){
$currentPage = $minimumNumberOfPage-1;
$previous = "<a href=\"$self?page=$currentPage\">Previous</a>";
$first = "<a href=\"$self?page=1\">First</a>";
} else{
$previous = "<a href=\"#\" class=\"disable\">Previous</a>";
$first = "<a href=\"#\" class=\"disable\">First</a>";
}
if($totalNumberOfPages>$minimumNumberOfPage){
$currentPage = $minimumNumberOfPage+1;
$next = "<a href=\"$self?page=$currentPage\">Next</a>";
$last = "<a href=\"$self?page=$totalNumberOfPages\">Last</a>";
} else {
$next = "<a href=\"#\" class=\"disable\">Next</a>";
$last = "<a href=\"#\" class=\"disable\">Last</a>";
}
//*************************FOR INSERT AND UPDATE CALL OBJECT FROM CMS MANNAGER*********************

if(isset($_REQUEST['action']) && $_REQUEST['action']=='add_new_user')
{
$insertUser= $userDetail->addUser($_REQUEST,$_FILES);
if(isset($_REQUEST['uId']) && $_REQUEST['uId']!=''){
$returnUrlAddress ='admin-users.php?msg=2&page='.$_REQUEST['url'];
echo '<script>document.location.href="'.$returnUrlAddress.'"</script>';
exit();
} else {
echo '<script>document.location.href="admin-users.php?msg=1";</script>';
exit();
}
}

//******************************OBJECT FOR THE LISTING*************************************************
if($pg_Name=='userlist'){
$userList = $userDetail->getUserList($_REQUEST,$limitStartfrom,$numberOfRecordsPerPage);
}
//*****************************SHOW VALUE ON EDITING***************************************************
$name=$usr_name=$password=$access_level=$status='';
if(isset($_REQUEST['uId']) && $_REQUEST['uId']!='' ) {
$editList= $userDetail->getUserForEdit($_REQUEST['uId']);
if(count($editList)>0){
$name=$editList[0]['name'];
$usr_name=$editList[0]['usr_name'];
$password=$editList[0]['decrypt_password'];
$access_level=$editList[0]['access_level'];
$status=$editList[0]['status'];
}
}
//*********************************************************************************

action user


include("include/common.inc.php");
include("./include/headerAdmin.php");
require_once("include/DatabaseManager.php");

if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'delUser' && isset(   $_REQUEST['uId']) && $_REQUEST['uId'] != ''){
  $delete = "DELETE FROM admin_users WHERE usrid='".$_REQUEST['uId']."'";
mysql_query($delete);
$result = "admin-users.php?".$_REQUEST['url']."&deleted=true";
echo '<script>document.location.href="'.$result.'"</script>';
    }

if(isset($_REQUEST['action']) && $_REQUEST['action']=="deactive" ){
if(!empty($_POST['chk'])){
foreach($_POST['chk'] as $val){
$query='UPDATE admin_users SET status="0" WHERE  usrid="'.$val.'"';
mysql_query($query);
$result = "admin-users.php?start=".$_POST['urlForDeleteAndDeactivate']."&deactive=true";
echo '<script>document.location.href="'.$result.'"</script>';
    }
}
}
else {
if(!empty($_POST['chk'])) {
foreach($_POST['chk'] as $val){
$del = "delete from admin_users where usrid='".$val."'";
mysql_query($del);
$result = "admin-users.php?start=".$_POST['urlForDeleteAndDeactivate']."&deleted=true";
echo '<script>document.location.href="'.$result.'"</script>';
}
}
}

$name=$usr_name=$password=$access_level=$status='';
if(isset($_REQUEST['action']) && $_REQUEST['action'] =='add_new_user' ) {
if(isset($_REQUEST['uId']) && $_REQUEST['uId']!='' ) {
$query = 'UPDATE admin_users SET name="'.$_REQUEST['name'].'",usr_name="'.$_REQUEST['usr_name'].'",password="'.md5($_REQUEST['password']).'",access_level="'.$_REQUEST['access_level'].'",status="'.$_REQUEST['status'].'",decrypt_password="'.$_REQUEST['password'].'" WHERE usrid="'.$_REQUEST['uId'].'"';
$dbCon->executeInsert($query);
$result = "admin-users.php?".$_REQUEST['url']."&msg=1";
echo '<script>document.location.href="'.$result.'"</script>';

} else {
$query='INSERT INTO `admin_users`(name,usr_name,password,access_level,status,decrypt_password)VALUES("'.$_REQUEST['name'].'","'.$_REQUEST['usr_name'].'","'.md5($_REQUEST['password']).'","'.$_REQUEST['access_level'].'","'.$_REQUEST['status'].'","'.$_REQUEST['password'].'")';
$dbCon->executeInsert($query);
$result = "admin-users.php?msg=2";
echo '<script>document.location.href="'.$result.'"</script>';
}
}

$name=$usr_name=$password=$access_level=$status='';
if(isset($_REQUEST['uId']) && $_REQUEST['uId']!='' ) {
$selectAll="SELECT * FROM `admin_users` WHERE usrid='".$_REQUEST['uId']."'";
$result = $dbCon->executeQuery($selectAll,1);
if(count($result)>0){
$name=$result[0]['name'];
$usr_name=$result[0]['usr_name'];
$password=$result[0]['decrypt_password'];
$access_level=$result[0]['access_level'];
$status=$result[0]['status'];
}
}


if(isset($_REQUEST['action']) && $_REQUEST['action'] =='userStatus') {
$status='';
$url='';
if($_REQUEST['status']=='0'){
$status=1;
} else{
$status=0;
}
$update="UPDATE admin_users SET status='".$status."' WHERE usrid=".$_REQUEST['id'];
mysql_query($update);
$result ='admin-users.php?'.$_REQUEST['url'];
echo '<script>document.location.href="'.$result.'"</script>';
}


Manager user


class userManager
{
function addUser($arr,$files)
{

   require_once(COMM_PATH."DatabaseManager.php");
$dbCon= new DatabaseManager();

if(isset($_REQUEST['uId']) && $_REQUEST['uId']!=''){
$query = 'UPDATE admin_users SET name="'.$_REQUEST['name'].'",usr_name="'.$_REQUEST['usr_name'].'",password="'.md5($_REQUEST['password']).'",access_level="'.$_REQUEST['access_level'].'",status="'.$_REQUEST['status'].'",decrypt_password="'.$_REQUEST['password'].'" WHERE usrid="'.$_REQUEST['uId'].'"';
$result=$dbCon->executeUpdate($query);

} else {

$query='INSERT INTO `admin_users`(name,usr_name,password,access_level,status,decrypt_password)VALUES("'.$_REQUEST['name'].'","'.$_REQUEST['usr_name'].'","'.md5($_REQUEST['password']).'","'.$_REQUEST['access_level'].'","'.$_REQUEST['status'].'","'.$_REQUEST['password'].'")';
$dbCon->executeUpdate($query);
//return $result;
}
}


   function getUserList($arr,$limitStart=null,$recodsShow=null)
{
require_once(COMM_PATH."DatabaseManager.php");
$db= new DatabaseManager();
$query="SELECT * FROM `admin_users` ORDER BY usrid DESC LIMIT $limitStart,$recodsShow";
$result=$db->executeQuery($query);
return $result;
}


function getUserForEdit($uId)
{
require_once(COMM_PATH."DatabaseManager.php");
$db= new DatabaseManager();
$query='SELECT * FROM `admin_users` WHERE usrid="'.$uId.'"';
$result=$db->executeQuery($query);
return $result;
}

function deleteUser($uId){
require_once(COMM_PATH."DatabaseManager.php");
$dbCon= new DatabaseManager();
$query='DELETE FROM admin_users WHERE usrid="'.$_REQUEST['uId'].'"';
$result=$dbCon->executeUpdate($query);
return $result;
}

function updateAllstatus($uId){
require_once(COMM_PATH."DatabaseManager.php");
$dbCon= new DatabaseManager();
foreach($uId as $val){
$query='UPDATE admin_users SET status="0" WHERE  usrid="'.$val.'"';
$result=$dbCon->executeUpdate($query);
}
//return $result;
}

function delAllUser($uId){
require_once(COMM_PATH."DatabaseManager.php");
$dbCon= new DatabaseManager();
foreach($uId as $val){
$query='delete from admin_users where usrid="'.$val.'"';
$result=$dbCon->executeUpdate($query);
}
}


function count_User(){
require_once(COMM_PATH."DatabaseManager.php");
$dbCon= new DatabaseManager();
$query='SELECT COUNT(*) as cnt FROM admin_users';
$result=$dbCon->executeQuery($query);
return $result[0]['cnt'];
}
}
/////////////////////////////////////////////////////////////////////init//////////////////////////////////////////////////////


require_once(ADMIN_LIB_PATH."user/userManager.php");
$userDetail = new userManager();//object for userManager class for accesing all function in userManager

//****************************PAGINATION START FROM HERE*********************************************
$numberOfRecordsPerPage = 2;
$minimumNumberOfPage = 1;
if(isset($_REQUEST['page']) && $_REQUEST['page']!=''){
$minimumNumberOfPage = $_REQUEST['page'];
}
$limitStartfrom = ($minimumNumberOfPage-1)*$numberOfRecordsPerPage;
//There is an object for count the number of record, From these we get number of page.................
$totalNumberOfRecords = $userDetail->count_User();
$totalNumberOfPages = ceil($totalNumberOfRecords/$numberOfRecordsPerPage);
$self = $_SERVER['PHP_SELF'];
if($minimumNumberOfPage>1){
$currentPage = $minimumNumberOfPage-1;
$previous = "<a href=\"$self?page=$currentPage\">Previous</a>";
$first = "<a href=\"$self?page=1\">First</a>";
} else{
$previous = "<a href=\"#\" class=\"disable\">Previous</a>";
$first = "<a href=\"#\" class=\"disable\">First</a>";
}
if($totalNumberOfPages>$minimumNumberOfPage){
$currentPage = $minimumNumberOfPage+1;
$next = "<a href=\"$self?page=$currentPage\">Next</a>";
$last = "<a href=\"$self?page=$totalNumberOfPages\">Last</a>";
} else {
$next = "<a href=\"#\" class=\"disable\">Next</a>";
$last = "<a href=\"#\" class=\"disable\">Last</a>";
}
//*************************FOR INSERT AND UPDATE CALL OBJECT FROM CMS MANNAGER*********************

if(isset($_REQUEST['action']) && $_REQUEST['action']=='add_new_user')
{
$insertUser= $userDetail->addUser($_REQUEST,$_FILES);
if(isset($_REQUEST['uId']) && $_REQUEST['uId']!=''){
$returnUrlAddress ='admin-users.php?msg=2&page='.$_REQUEST['url'];
echo '<script>document.location.href="'.$returnUrlAddress.'"</script>';
exit();
} else {
echo '<script>document.location.href="admin-users.php?msg=1";</script>';
exit();
}
}

//******************************OBJECT FOR THE LISTING*************************************************
if($pg_Name=='userlist'){
$userList = $userDetail->getUserList($_REQUEST,$limitStartfrom,$numberOfRecordsPerPage);
}
//*****************************SHOW VALUE ON EDITING***************************************************
$name=$usr_name=$password=$access_level=$status='';
if(isset($_REQUEST['uId']) && $_REQUEST['uId']!='' ) {
$editList= $userDetail->getUserForEdit($_REQUEST['uId']);
if(count($editList)>0){
$name=$editList[0]['name'];
$usr_name=$editList[0]['usr_name'];
$password=$editList[0]['decrypt_password'];
$access_level=$editList[0]['access_level'];
$status=$editList[0]['status'];
}
}
//***************************js******************************************
function validateAddUser(){
if(isEmpty(document.getElementById('first_name').value)){
if(document.getElementById('server_error_msg'))
document.getElementById('server_error_msg').style.display='none';
document.getElementById('error').style.display='';
document.getElementById('error').innerHTML='Please Enter First Name.';
return false;
}

if(isEmpty(document.getElementById('last_name').value)){
if(document.getElementById('server_error_msg'))
document.getElementById('server_error_msg').style.display='none';
document.getElementById('error').style.display='';
document.getElementById('error').innerHTML='Please Enter Last Name.';
return false;
}

if(validateHtml(document.getElementById('first_name').value)){
if(document.getElementById('server_error_msg'))
document.getElementById('server_error_msg').style.display='none';
document.getElementById('error').style.display='';
document.getElementById('error').innerHTML='HTML tags are not allowed .';
return false;
}

if(validateHtml(document.getElementById('last_name').value)){
if(document.getElementById('server_error_msg'))
document.getElementById('server_error_msg').style.display='none';
document.getElementById('error').style.display='';
document.getElementById('error').innerHTML='HTML tags are not allowed .';
return false;
}

   if(document.getElementById('signupDOBMonth').value=='0'){
  if(document.getElementById('server_error_msg')){
document.getElementById('server_error_msg').style.display='none';
  }
document.getElementById('error').style.display='';
document.getElementById('error').innerHTML='Select month of Date of Birth';
  return false;
}
if(document.getElementById('signupDOBDay').value=='0'){
  if(document.getElementById('server_error_msg')){
document.getElementById('server_error_msg').style.display='none';
  }
document.getElementById('error').style.display='';
document.getElementById('error').innerHTML='Select day of Date of Birth';
  return false;
}
if(document.getElementById('signupDOBYear').value=='0'){
  if(document.getElementById('server_error_msg')){
document.getElementById('server_error_msg').style.display='none';
  }
document.getElementById('error').style.display='';
document.getElementById('error').innerHTML='Select Year of Date of Birth';
  return false;
}
 
if(isEmpty(document.getElementById('email').value)){
if(document.getElementById('server_error_msg'))
document.getElementById('server_error_msg').style.display='none';
document.getElementById('error').style.display='';
document.getElementById('error').innerHTML='Please Enter Email.';
return false;
}
if(!isEmail(document.getElementById('email').value)){
if(document.getElementById('server_error_msg'))
document.getElementById('server_error_msg').style.display='none';
document.getElementById('error').style.display='';
document.getElementById('error').innerHTML='Please Enter Valid Email Address ! It should be @ format.';
return false;
}

if(validateHtml(document.getElementById('email').value)){
if(document.getElementById('server_error_msg'))
document.getElementById('server_error_msg').style.display='none';
document.getElementById('error').style.display='';
document.getElementById('error').innerHTML='HTML tags are not allowed.';
return false;
}

if(isEmpty(document.getElementById('u_pass').value)){
if(document.getElementById('server_error_msg'))
document.getElementById('server_error_msg').style.display='none';
document.getElementById('error').style.display='';
document.getElementById('error').innerHTML='Please Enter Password.';
return false;
}

if(validateHtml(document.getElementById('u_pass').value)){
if(document.getElementById('server_error_msg'))
document.getElementById('server_error_msg').style.display='none';
document.getElementById('error').style.display='';
document.getElementById('error').innerHTML='HTML tags are not allowed.';
return false;
}

if(document.getElementById('contact_country').value=='0'){
  if(document.getElementById('server_error_msg')){
document.getElementById('server_error_msg').style.display='none';
  }
document.getElementById('error').style.display='';
document.getElementById('error').innerHTML='please select a country';
  return false;
}
 
if(isEmpty(document.getElementById('city').value)){
  if(document.getElementById('server_error_msg')){
document.getElementById('server_error_msg').style.display='none';
  }
document.getElementById('error').style.display='';
document.getElementById('error').innerHTML='please enter a City';
  return false;
}
file = document.getElementById('pic').value;
if(file!=''){
size = file.length -4;
ext =  file.substring(size) ;
if(ext != ".gif" && ext != ".jpeg" && ext != ".png" && ext != ".jpg" && ext != ".GIF" && ext != "JPEG" && ext != ".PNG" && ext != ".JPG")
{
if(document.getElementById('server_error_msg')){
document.getElementById('server_error_msg').style.display='none';
  }
document.getElementById('error').style.display='';
document.getElementById('error').innerHTML='please select a jpg,png or gif format image';
return false;
}
}
if (document.getElementById('Contact_Sports_other').checked==true)
{
if(isEmpty(document.getElementById('sports_other').value)){
  if(document.getElementById('server_error_msg')){
document.getElementById('server_error_msg').style.display='none';
  }
document.getElementById('error').style.display='';
document.getElementById('error').innerHTML='please enter other sports name.';
  return false;
}
}
if (document.getElementById('Outdoor_Activities_other').checked==true)
{
if(isEmpty(document.getElementById('Act
////////////////////////////////////JS My////////////////////////////////////////////////////////////////////////////////////////
function Ajax() {
  this.req = null;
  this.url = null;
  this.status = null;
  this.statusText = '';
  this.method = 'GET';
  this.async = true;
  this.dataPayload = null;
  this.readyState = null;
  this.responseText = null;
  this.responseXML = null;
  this.handleResp = null;
  this.responseFormat = 'text', // 'text', 'xml', 'object'
  this.mimeType = null;
  this.headers = [];

  
  this.init = function() {
    var i = 0;
    var reqTry = [ 
      function() { return new XMLHttpRequest(); },
      function() { return new ActiveXObject('Msxml2.XMLHTTP') },
      function() { return new ActiveXObject('Microsoft.XMLHTTP' )} ];
      
    while (!this.req && (i < reqTry.length)) {
      try { 
        this.req = reqTry[i++]();
      } 
      catch(e) {}
    }
    return true;
  };
  this.doGet = function(url, hand, format) {
    this.url = url;
    this.handleResp = hand;
    this.responseFormat = format || 'text';
    this.doReq();
  };
  this.doPost = function(url, dataPayload, hand, format) {
    this.url = url;
    this.dataPayload = dataPayload;
    this.handleResp = hand;
    this.responseFormat = format || 'text';
    this.method = 'POST';
    this.doReq();
  };
  this.doReq = function() {
    var self = null;
    var req = null;
    var headArr = [];
    
    if (!this.init()) {
      alert('Could not create XMLHttpRequest object.');
      return;
    }
    req = this.req;
    req.open(this.method, this.url, this.async);
    if (this.method == "POST") {
      this.req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    }
    if (this.method == 'POST') {
      req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    }
    self = this;
    req.onreadystatechange = function() {
      var resp = null;
      self.readyState = req.readyState;
      if (req.readyState == 4) {
        self.status = req.status;
        self.statusText = req.statusText;
        self.responseText = req.responseText;
        self.responseXML = req.responseXML;
        
        switch(self.responseFormat) {
          case 'text':
            resp = self.responseText;
            break;
          case 'xml':
            resp = self.responseXML;
            break;
          case 'object':
            resp = req;
            break;
        }
        
        if (self.status > 199 && self.status < 300) {
          if (!self.handleResp) {
            //alert('No response handler defined ' + 'for this XMLHttpRequest object.');
            return;
          }
          else {
            self.handleResp(resp);
          }
        }
        
        else {
          self.handleErr(resp);
        }
      }
    }
    req.send(this.dataPayload);
  };
  this.abort = function() {
    if (this.req) {
      this.req.onreadystatechange = function() { };
      this.req.abort();
      this.req = null;
    }
  };
  this.handleErr = function() {
    var errorWin;
    // Create new window and display error
    try {
      errorWin = window.open('', 'errorWin');
      errorWin.document.body.innerHTML = this.responseText;
    }
    // If pop-up gets blocked, inform user
    catch(e) {
      alert('An error occurred, but the error message cannot be' +
      ' displayed because of your browser\'s pop-up blocker.\n' +
      'Please allow pop-ups from this Web site.');
    }
  };
  this.setMimeType = function(mimeType) {
    this.mimeType = mimeType;
  };
  this.setHandlerResp = function(funcRef) {
    this.handleResp = funcRef;
  };
  this.setHandlerErr = function(funcRef) {
    this.handleErr = funcRef; 
  };
  this.setHandlerBoth = function(funcRef) {
    this.handleResp = funcRef;
    this.handleErr = funcRef;
  };
  this.setRequestHeader = function(headerName, headerValue) {
    this.headers.push(headerName + ': ' + headerValue);
  };
  
}
/////////////////////////////////////db online//////////////////////////////////

/**
 * The SystemDatabaseManager class provides the mechanism for interacting with the system database
 *
 * The class is written using the Singleton pattern.
 * Here is how a reference to an instance of the class is obtained:
 * <code>
 * $systemDatabaseManager = SystemDatabaseManager::getInstance();
 * </code>
 *
 * @package Database
 * @author Bhart Garg
 * made $userName, $host and $password as private members
 * replaced constant for database with a private member
 */
 
class DatabaseManager  {

// for offline 
private  static $host = 'localhost';
private  static $userName = 'trip';
private static $password = 'trip';
private static $dbName = 'trip_whale';  

public $conn = '';

function __construct() {
$this->conn = $this->connectToServer(DatabaseManager::$host, DatabaseManager::$userName, DatabaseManager::$password);
$this->selectDatabase(DatabaseManager::$dbName, $this->conn);
}


/**
* executes a SELECT query in the database
*
* @access public
* @param $query The SQL SELECT query to execute
* @param $comment An optional comment explaining the query
*
* @return the result set on success, or false on error
*/
public function executeQuery($query) {
$result = mysql_query($query);
if ($result === false) {
$this->closeConnection($this->conn);
exit;
}
// extract data from results, returning an associative array
$rows = Array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
}
/**
* executes a SELECT query in the database
*
* @access public
* @param $query The SQL SELECT query to execute
* @param $comment An optional comment explaining the query
*
* @return the result set on success, or false on error
*/
public function executeUpdate($query) {
$result = mysql_query($query);
if ($result === false) {
$this->closeConnection($this->conn);
exit;
}
if(mysql_affected_rows()>0){
return true;
} else {
return false;
}
}

/**
* returns last inserted id
*
* @param NA
* @param NA
*
  * @return last insert id on success, or false on error
*/
public function lastInsertId(){
return mysql_insert_id();
}


function connectToServer($DBHost, $DBUsername, $DBPassword) {

$connection = mysql_connect($DBHost, $DBUsername, $DBPassword);
if ($connection === false) {
echo "Unable to connect to the database on $DBHost with username $DBUsername";
// through to maintenance page
exit;
}
return $connection;
}

function selectDatabase($database, $connection) {
$success = mysql_select_db($database, $connection);
if ($success === false) {
echo "Failed to select database '$database'";
return false;
}
return true;
}
function closeConnection($connection) {
$result = mysql_close($connection);
if ($result === false) {
exit;
}
}

}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 * The SystemDatabaseManager class provides the mechanism for interacting with the system database
 *
 * The class is written using the Singleton pattern.
 * Here is how a reference to an instance of the class is obtained:
 * <code>
 * $systemDatabaseManager = SystemDatabaseManager::getInstance();
 * </code>
 *
 * @package Database
 * @author Bhart Garg
 * made $userName, $host and $password as private members
 * replaced constant for database with a private member
 */
 
class DatabaseManager  {

// for offline 
private  static $host = 'localhost';
private  static $userName = 'root';
private static $password = '';
private static $dbName = 'trip_whale';  

public $conn = '';
private static $instance; 
function __construct() {
$this->conn = $this->connectToServer(DatabaseManager::$host, DatabaseManager::$userName, DatabaseManager::$password);
$this->selectDatabase(DatabaseManager::$dbName, $this->conn);
}


/**
* executes a SELECT query in the database
*
* @access public
* @param $query The SQL SELECT query to execute
* @param $comment An optional comment explaining the query
*
* @return the result set on success, or false on error
*/
public function executeQuery($query) {
$result = mysql_query($query);
if ($result === false) {
$this->closeConnection($this->conn);
exit;
}
// extract data from results, returning an associative array
$rows = Array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
}
/**
* executes a SELECT query in the database
*
* @access public
* @param $query The SQL SELECT query to execute
* @param $comment An optional comment explaining the query
*
* @return the result set on success, or false on error
*/
public function executeUpdate($query) {
$result = mysql_query($query);
if ($result === false) {
$this->closeConnection($this->conn);
exit;
}
if(mysql_affected_rows()>0){
return true;
} else {
return false;
}
}

/**
* returns last inserted id
*
* @param NA
* @param NA
*
  * @return last insert id on success, or false on error
*/
public function lastInsertId(){
return mysql_insert_id();
}


function connectToServer($DBHost, $DBUsername, $DBPassword) {

$connection = mysql_connect($DBHost, $DBUsername, $DBPassword);
if ($connection === false) {
echo "Unable to connect to the database on $DBHost with username $DBUsername";
// through to maintenance page
exit;
}
return $connection;
}

function selectDatabase($database, $connection) {
$success = mysql_select_db($database, $connection);
if ($success === false) {
echo "Failed to select database '$database'";
return false;
}
return true;
}
function closeConnection($connection) {
$result = mysql_close($connection);
if ($result === false) {
exit;
}
}
//singlton method to access the classs

public static function getInstance() {
if (! isset ( self::$instance )) {
$c = __CLASS__;
self::$instance = new $c ( );
}
return self::$instance;
 }


Thursday 17 November 2011

Common Javascript for validation


// JavaScript Document


// get element by id
function getObject(val){
return document.getElementById(val);
}


function trim(b)
{
var i=0;
while(b.charAt(i)==" ")
{
i++;
}
b=b.substring(i,b.length);
len=b.length-1;
while(b.charAt(len)==" ")
{
len--;
}
b=b.substring(0,len+1);
return b;
}

function checkAtLeastOneBox(name) {

count = 0;
elements = document.getElementsByName(name);
len = elements.length;

for (var i = 0; i < len; i++) {
var e = elements[i];
if (e.checked) {
count=count+1;
}
}

if (count == 0){
return false;
}
else {
return true;
}
}


function isCharsInBag (s, bag)
  {
    var i;
    // Search through string's characters one by one.
    // If character is in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) return false;
    }
    return true;
 }

//function to check valid zip code
function isZIP(s)
  {
    return isAlphaNumeric(s);
 }


function isValidUrlAddress(strUrl) {// not working
 
   var v = new RegExp();
    v.compile("[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
    if (!v.test(strUrl)) {
        return false;
    }
return true;
}



function checkURL(value) {

var urlregex = new RegExp("^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([0-9A-Za-z]+\.)");
if(urlregex.test(value))
{
return(true);
}
return(false);
}

function isValidUrl(strUrl) {
   var v = new RegExp();
    v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
    if (!v.test(strUrl)) {
        return false;
    }
return true;
}

function isValidUrl2(strUrl) {
   var v = new RegExp();
    v.compile("^[A-Za-z0-9-_:\/]+\\.[A-Za-z0-9-_%&\?\/.=]+\\.[A-Za-z]+$");
    if (!v.test(strUrl)) {
        return false;
    }
return true;
 }
function isChar(s){
s=trim(s);
return isCharsInBag (s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ");
}


function isName(s){
s=trim(s);
return isCharsInBag (s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ- ");
}
function isPassword(s)
{

s=trim(s);
return isCharsInBag (s, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_");
}

//function to check valid Telephone,. Fax no. etc
function isPhone(s)
  {

return isCharsInBag (s, "0123456789-+(). ");//simple test

var PNum = new String(s);

// 555-555-5555
// (555)555-5555
// (555) 555-5555
// 555-5555

    // NOTE: COMBINE THE FOLLOWING FOUR LINES ONTO ONE LINE.

var regex = /^[0-9]{3,3}\-[0-9]{3,3}\-[0-9]{4,4}$|^\([0-9]{3,3}\) [0-9]{3,3}\-[0-9]{4,4}$|^\([0-9]{3,3}\)[0-9]{3,3}\-[0-9]{4,4}$|^[0-9]{3,3}\-[0-9]{4,4}$/;

// var regex = /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/; //(999) 999-9999 or (999)999-9999
if( regex.test(PNum))
return true;
else
return false;

  }

function isAlphaNumeric(s){
    return isCharsInBag (s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789- ");
}

function isUserName(s){
s=trim(s);
    return isCharsInBag (s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.");
}

function isEmpty(s)
{
s=trim(s);
 return ((s == null) || (s.length == 0));
}

//function to check valid email id
function isEmail(s)
{

var regex = /(^[a-z]([a-z_\.]*)@([a-z_\.]*)([.][a-z]{3})$)|(^[a-z]([a-z_\.]*)@([a-z_\.]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i
var regex = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return regex.test(s);

}


function isInteger (s)
   {
      var i;

      if (isEmpty(s))
      if (isInteger.arguments.length == 1) return 0;
      else return (isInteger.arguments[1] == true);

      for (i = 0; i < s.length; i++)
      {
         var c = s.charAt(i);

         if (!isDigit(c)) return false;
      }

      return true;
}

function isDigit (c)
{
  return ((c >= "0") && (c <= "9"))
}



  //set focus on el or global variable gl_el;
  function setFocus(el){
if(el != "undefined"){
document.getElementById(el).focus();
setAlertStyle(el);
// addEvent(document.getElementById(el),'onblur',function(){ alert('hello!'); })
}else if(typeof gl_el != "undefined"){
gl_el.focus();
}
return true;

  }
 

  function setAlertStyle(el){
document.getElementById(el).style.border = '2px solid';
document.getElementById(el).style.borderColor = '000';
  }
 
  function unsetAlertStyle(el){
document.getElementById(el).style.border = '2px solid';
document.getElementById(el).style.borderColor = '#f0f0f1';
  }

function SetAllCheckBoxes(FormName,FieldName)
{
var isChecked=document.getElementById('checkAll').checked;

if(isChecked==true){
var CheckValue='true';

}
else
{
var CheckValue='';
}

if(!FormName)
return;
var objCheckBoxes = document.forms[FormName].elements[FieldName];

if(!objCheckBoxes)
return;
var countCheckBoxes = objCheckBoxes.length;

if(!countCheckBoxes)
objCheckBoxes.checked = CheckValue;
else
// set the check value for all check boxes
for(var i = 0; i < countCheckBoxes; i++)
{
objCheckBoxes[i].checked = CheckValue;


}
}

function isAllcheckBoxSelected(formObj,checkBoxName){
var status = false;
var countCheckBoxes = 0;
var objCheckBoxes = formObj.elements[checkBoxName];
countCheckBoxes = objCheckBoxes.length;
if(countCheckBoxes!=0){
for(var i = 0; i <countCheckBoxes; i++){
if(objCheckBoxes[i].checked==true){
status = true;
}else{
status = false;
break;
}
}
}if(!countCheckBoxes) {
if(objCheckBoxes.checked==true){
status = true;
}else {
status = false;
}
}
return status;
}


function checkMasterCheckBox(checkBoxObj,formName,checkBoxName,masterCheckBoxName){
allCheckBoxCheckedStatus = false;
formObj = getObject(formName);
masterCheckBoxObj = getObject(masterCheckBoxName);
allCheckBoxCheckedStatus = isAllcheckBoxSelected(formObj,checkBoxName);
//alert(allCheckBoxCheckedStatus);
if(checkBoxObj.checked==true){
if(allCheckBoxCheckedStatus==true){
masterCheckBoxObj.checked = true;
}
}else{
masterCheckBoxObj.checked = false;
}

}


function showchkbox(){
$(document).ready(function(){
$('#chkTab').toggle('slow');
$('#downarrow').toggle('slow');
});
}

/**
 * shows a popup<br />
 * depends on jquery<br />
 * there should be empty div named winhidelayer on page.<br />
 * @param id of popup div
 */
function showPopup(id){
    var height = $(window).height();
    var winwidth = $(window).width();

try{

$('#winhidelayer').show();
 $('#winhidelayer').css({
'left' : 0,
'top' :0,
'height' : height,
'width' : winwidth

});
}catch(error){
}
$('#'+id).show();
var snpopup = $('#'+id);
    var width = $(document).width();

    snpopup.css({
        'left' : width/2 - (snpopup.width() / 2),
        'top' : height/2 - (snpopup.height() / 2),
        'z-index' : 1000000                      
    });
}

/**
 * hide a popup<br />
 * depends on jquery<br />
 * there should be empty div named winhidelayer on page.<br />
 * @param id of popup div
 */
function hidePopup(id){
try{
$('#winhidelayer').hide();
}catch(error){
}
$('#'+id).hide();
}

/*
function isleap(yr)
{
 //var yr=document.getElementById("year").value;
 if ((parseInt(yr)%4) == 0)
 {
  if (parseInt(yr)%100 == 0)
  {
    if (parseInt(yr)%400 != 0)
    {
    //alert("Not Leap");
    return false;
    }
    if (parseInt(yr)%400 == 0)
    {
   // alert("Leap");
    return true;
    }
  }
  if (parseInt(yr)%100 != 0)
  {
   // alert("Leap");
    return true;
  }
 }
 if ((parseInt(yr)%4) != 0)
 {
    //alert("Not Leap");
    return false;
 }
}
*/


function daysInMonth(iMonth,iYear)
{


var days=32 - new Date(iYear, iMonth, 32).getDate();

return days;

}


 /*function CompDate(adate,bdate,msg)
{
start = document.getElementById('day').value+'-'+document.getElementById('month').value+'-'+document.getElementById('year').value+'-'+document.getElementById('hour').value+'-'+document.getElementById('min').value;
end = document.getElementById('day2').value+'-'+document.getElementById('month2').value+'-'+document.getElementById('year2').value+'-'+document.getElementById('hour2').value+'-'+document.getElementById('min2').value;
//alert(start); alert(end);
a = start.split('-');
b = end.split('-');
var sDate = new Date(a[2],a[0]-1,a[1],a[3],a[4]);
var eDate = new Date(b[2],b[0]-1,b[1],b[3],b[4]);

if (sDate <= eDate)
{
alert('right');
return true;
}
else
{
   alert('wrong');
return false;
}
}




var startDate=new Date();
startDate.setFullYear(2010,0,14);
var endDate  =new Date();
endDate.setFullYear(2010,0,14);


if (startDate>endDate)
  {
  alert("Today is before 14th January 2010");
  }
else if(startDate<endDate)
  {
  alert("Today is after 14th January 2010");
  }
   else if(startDate=endDate){
   
alert('Equal');
 }
 */



function validateZipCode(elementValue){
      var zipCodePattern = /^\d{5}$|^\d{5}-\d{4}$/;
      return zipCodePattern.test(elementValue);
 }

function allValid(s){
s=trim(s);
return isCharsInBag (s, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz. ");
}

function priceValid(s){
s=trim(s);
return isCharsInBag (s, "0123456789. ");
}
function validateHtml(str){
 if(str.match(/([\<])([^\>]{1,})*([\>])/i)==null)
return false;
 else
return true;
}
function isFloatNumeric(s){
   return isCharsInBag (s, "0123456789. ");
}