

// Copyright 2007, Google Inc.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//  1. Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//  3. Neither the name of Google Inc. nor the names of its contributors may be
//     used to endorse or promote products derived from this software without
//     specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Sets up google.gears.*, which is *the only* supported way to access Gears.
//
// Circumvent this file at your own risk!
//
// In the future, Gears may automatically define google.gears.* without this
// file. Gears may use these objects to transparently fix bugs and compatibility
// issues. Applications that use the code below will continue to work seamlessly
// when that happens.

(function() {
  // We are already defined. Hooray!
  if (window.google && google.gears) {
    return;
  }

  var factory = null;

  // Firefox
  if (typeof GearsFactory != 'undefined') {
    factory = new GearsFactory();
  } else {
    // IE
    try {
      factory = new ActiveXObject('Gears.Factory');
      // privateSetGlobalObject is only required and supported on IE Mobile on
      // WinCE.
      if (factory.getBuildInfo().indexOf('ie_mobile') != -1) {
        factory.privateSetGlobalObject(this);
      }
    } catch (e) {
      // Safari
      if ((typeof navigator.mimeTypes != 'undefined')
           && navigator.mimeTypes["application/x-googlegears"]) {
        factory = document.createElement("object");
        factory.style.display = "none";
        factory.width = 0;
        factory.height = 0;
        factory.type = "application/x-googlegears";
        document.documentElement.appendChild(factory);
      }
    }
  }

  // *Do not* define any objects if Gears is not installed. This mimics the
  // behavior of Gears defining the objects in the future.
  if (!factory) {
    return;
  }

  // Now set up the objects, being careful not to overwrite anything.
  //
  // Note: In Internet Explorer for Windows Mobile, you can't add properties to
  // the window object. However, global objects are automatically added as
  // properties of the window object in all browsers.
  if (!window.google) {
    google = {};
  }

  if (!google.gears) {
    google.gears = {factory: factory};
  }
})();




/** ViewState.js 
 * @author litie@shopex.cn
 * (c) ShopEx Team < www.shope.cn >

 *本JS基于Mootools JS Framework构建.
 
 *   本JS依赖shop/common/footer.html  <span id='shareObjectsStorage_panel' style='position:absolute'></span>定义.
 *  依赖statics/sop.swf
 
 * ViewState利用各种客户端浏览器特性,致力模拟一个用于存放少量数据的仓库.

 * 并且在浏览器关闭后,仍能将数据缓存在客户端.

* 用法:
           window.withUStatus(function(status){
              //status 就是客户端存储仓库对象。
              //you can:
              
              status.set('key',value);
              status.get('key');
           
           });
	 
     且:window.uStatus 指向 status;可随时调用
*
*
*/

(function(){
	function csop(){
	  return  new Swiff(Shop.set.path+"statics/sop.swf",{
					  id:'shareObjectsStorage',
					  container:$('shareObjectsStorage_panel'),
					  width:'1',
					  height:'1'
			});
    };
	csop();
    
	ViewState=new Class({
      initialize:function(){
           this.storage=getStorageMaster()||{};
		   return this;
	  },
	  set:function(key,vl){
        this.storage.setStorage=this.storage.setStorage||$empty;
        this.storage.setStorage(key,ts(vl));
        return this;
	  },
	  get:function(key,callback){
         this.storage.getStorage=this.storage.getStorage||$empty;
	     this.storage.getStorage(key,callback);
	  },
	  remove:function(key){
      
			if (!key || !this.storage) return false;
            this.storage.removeStorage=this.storage.removeStorage||$empty;
			this.storage.removeStorage(key);
            return this;
	  },
	  clear:function(){
			if (!this.storage)return false;
            this.storage.clearStorage=this.storage.clearStorage||$empty;
			this.storage.clearStorage();
            return this;
	  }
     });

	 //Private Function
	 function ev(v){
	   return v?Json.evaluate('(' + v + ')'):null;
	 };
	 function ts(v){
      return v?Json.toString(v):null;
	 };
	 
	 
	function getStorageMaster(){
       if(!!window.openDatabase)return OpenDatabase.init();    
       if (window.google && google.gears)return Gears.init();    
	   if(!!window.sessionStorage)return DomStorage.init();
	   if(window.ie)return UserData.init();	
	   if(Browser.Plugins.Flash.version>=6){
	      return  SharedObject.init();
	   }
	   return false;
	 };
     
     //google Gears
	 var Gears={
         init:function(){
               var db;
                 try {
                if(!google.gears.factory.create){
              
                  return SharedObject.init();
                };
                  db = google.gears.factory.create('beta.database');
                  if (db) {
                    db.open('database-shopex_viewstatus');
                    db.execute('create table if not exists status' +
                               ' (skey text, sval text)'); 
                     this.db=db;
                 
                  }else{
                     return false;
                  }
                } catch (ex) {
                 
				  return SharedObject.init();
                }
             
            return this;
         },
         setStorage:function(key, vl) {
                var rs=this.db.execute('select * from status where skey=?',[key]);
			    if(rs.isValidRow()){
                   var update=this.db.execute('update status set sval=? where skey=?',[vl,key]);
                                   rs.close();
                }else{
                   var insert=this.db.execute('insert into status values (?,?)',[key,vl]);
                   
                }

            },
            getStorage: function(key,callback) {

                    var rs=this.db.execute('select * from status where skey=?',[key]);
                    if(rs.isValidRow()){
                      callback(rs.field(1));
                    }else{
                      callback();
                      //console.info("nors");
                    }
                     rs.close();
                    
            },
            removeStorage: function(key) {
               this.db.execute('delete from status where skey=?',[key]);
            },
            clearStorage: function() {
               this.db.execute('drop table status');
            }
     }

	 //firefox2+ Ie8
	 var DomStorage={
			init: function() {
			    this.Master="firefox2+ Ie8";
				 if(!window.globalStorage){
				 csop();
				 return SharedObject.init();
				 }
				this._storage =globalStorage[location.hostname];
				return this;
			},
			setStorage: function(key, value) {
				this._storage.setItem(key, value);
				return true;
			},
			getStorage: function(key,callback) {
				var item = this._storage.getItem(key);
				var value = item ? item.value : null;
				callback(value);
			},
			removeStorage: function(key) {
				this._storage.removeItem(key);
				return true;
			},
			clearStorage: function() {
				if (this._storage.clear) {
					this._storage.clear();
				} else {
					for (i in this._storage) {
						if (this._storage[i].value) {
							this.remove(i);
						}
					}
				}
				return true;
			}
      };

	  
	  //ie6+
	  var UserData={
			 init: function() { 
			    this.Master="ie6+";
			    if(!window.ie)return false;
			    this._storage=new Element('span').setStyles({
				     'display':'none',
					 'behavior':"url('#default#userData')"
				   }).inject(document.body);
				 return this;
			},
			setStorage: function(key, value) {
					this._storage.setAttribute(key, value);
					this._storage.save('shopEX_VS');
				    return true;
			},
			getStorage: function(key,callback) {
			        this._storage.load('shopEX_VS');
				callback(this._storage.getAttribute(key));
			},
			removeStorage: function(key) {
					this._storage.removeAttribute(key);
					this._storage.save('shopEX_VS');
				return true;
			},
			clearStorage: function() {
					var date = new Date();
					date.setMinutes(date.getMinutes() - 1);
					this._storage.expires = date.toUTCString();
					this._storage.save("shopEX_VS");
					this._storage.load("shopEX_VS");
				   return true;
			}
	  };
	  
	  // All user agents with flash plugin >= 6

	  //if(!window.sessionStorage&&!window.ie&&!window.openDatabase);
	  var SharedObject={      
			 init: function() {
			   this.Master="flashSharedObject";
			   //if(!Browser.Plugins.Flash.version||Browser.Plugins.Flash.version<6)return false
			   this._storage=$('shareObjectsStorage');
               if(!this._storage.getStorage)return false;
			   return this;
			},
			setStorage: function(key, vl) {
					this._storage.setStorage(vl, key);
				return true;
			},
			getStorage: function(key,callback) {
				    callback(this._storage.getStorage(key));
			},
			removeStorage: function(key) {
			    this._storage.removeStorage(key);
				return true;
			},
			clearStorage: function() {
					this._storage.cleanStorage();
				return true;
			}
	  };
	  

	     
	  
	 //Safari (Version >= 3.1) openDatabase
var OpenDatabase ={
	init: function() {
         
	   this.Master="Safari (Version >= 3.1) openDatabase";
	   if(!window.openDatabase)return false;
	    ////console.log(" Safari (Version >= 3.1) openDatabase");
		this._storage = window.openDatabase("viewState", "1.0", "ShopEX48 ViewState Storage", 20000);

		this._createTable();
		return this;
	},
	setStorage: function(key, value) {
  
			this._storage.transaction(function(tx) {
				tx.executeSql("SELECT v FROM SessionStorage WHERE k = ?", [key], function(tx, result) {
					if (result.rows.length > 0) {
						tx.executeSql("UPDATE SessionStorage SET v = ?  WHERE k = ?", [value, key]);
						//console.info("u");
					} else {
						tx.executeSql("INSERT INTO SessionStorage (k, v) VALUES (?, ?)", [key, value]);
						//console.info("i");
					}
				});
			});
		return true;
	},
	getStorage: function(key,callback) {
			this._storage.transaction(function(tx) {	
				v=tx.executeSql("SELECT v FROM SessionStorage WHERE k = ?", [key], function(tx, result) {
				   if(result.rows.length>0)
                   return callback(result.rows.item(0).v);
                   callback(null);
				});
			});
	},
	removeStorage: function(key) {
			this._storage.transaction(function(tx) {	
				tx.executeSql("DELETE FROM SessionStorage WHERE k = ?", [key]);
			});
			return true;
	},
	clearStorage: function() {
			this._storage.transaction(function(tx) {
				tx.executeSql("DROP TABLE SessionStorage",[]);
			});
		return true;
	},
	_createTable: function() {
		this._storage.transaction(function(tx) {
		       tx.executeSql("SELECT COUNT(*) FROM SessionStorage", [], $empty, function(tx, error) {
            tx.executeSql("CREATE TABLE SessionStorage (k TEXT, v TEXT)", [], $empty);
        });
		});
	}
};


	 

})();






